当前位置:网站首页>5、 Pinda general permission system__ PD tools XXS (anti cross site script attack)
5、 Pinda general permission system__ PD tools XXS (anti cross site script attack)
2022-07-25 21:30:00 【The best is like water】
One 、pd-tools-xxs
pd-tools-xxs The module is positioned to prevent cross site scripting attacks (XSS), Through the user input on the page HTML / CSS / JavaScript And so on , Ensure that the input content conforms to the application specification , Ensure the safety of the system .
1.1、XSS Introduce
XSS: Cross-site scripting attacks (Cross Site Scripting), For discord CSS confusion , Therefore, the cross-site scripting attack is abbreviated as XSS.XSS A malicious attacker goes to web Malicious insert in the page Script Code , When the user browses the page , Embedded in web Inside Script Code will be executed , So as to achieve the purpose of malicious attacks on users . It's kind of like sql Inject .
XSS Attack principle :HTML It's a hypertext markup language , Distinguish text from markup by treating some characters in a special way , for example , Less than sign < Is seen as a HTML Start of label ,<title> And </title> The characters between are the page title and so on . When the content inserted in the dynamic page contains these special characters , The user's browser mistakenly thinks it's inserted HTML label , When these HTML The tag introduces a paragraph JavaScript Script time , These scripts will be executed in the user's browser . therefore , When these special characters can't be checked by dynamic page or there are errors in checking , There will be XSS Loophole .
1.2、AnitSamy Introduce
AnitSamy yes OWASP An open source project of , Through the input of the user HTML / CSS / JavaScript And so on , Make sure the input meets the application specification .AnitSamy Widely used in web Services are for storage and reflection XSS In the defense of .AnitSamy Of maven coordinate :
<dependency>
<groupId>org.owasp.antisamy</groupId>
<artifactId>antisamy</artifactId>
<version>1.5.7</version>
</dependency>
1.3、AnitSamy Introductory cases
First step : establish maven engineering antiSamy_demo And configuration pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.xbmu</groupId>
<artifactId>antiSamy_demo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.owasp.antisamy</groupId>
<artifactId>antisamy</artifactId>
<version>1.5.7</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
The second step : establish application.yml
server:
port: 9000
The third step : Create a policy file /resources/antisamy-test.xml, The contents of the file can be obtained from antisamy Of jar In the package for
notes : AntiSamy Yes Malicious code The filtering of depends on the policy file . The policy document specifies AntiSamy For each label 、 properties , Whether the policy file definition is strict or not , To determine the AntiSamy Yes XSS Vulnerability defense effect . stay AntiSamy Of jar In bag , Contains several commonly used policy files 
Step four : establish User Entity class
package com.xbmu.entity;
import lombok.Data;
@Data
public class User {
private int id;
private String name;
private int age;
}
Step five : establish UserController
package com.xbmu.controller;
import com.xbmu.entity.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping("/save")
public String save(User user){
System.out.println("UserController save.... " + user);
return user.getName();
}
}
Step six : establish /resources/static/index.html page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="/user/save">
id:<input type="text" name="id"><br>
name:<input type="text" name="name"><br>
age:<input type="text" name="age"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Step seven : Create startup class
package com.xbmu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AntiSamyApp {
public static void main(String[] args) {
SpringApplication.run(AntiSamyApp.class,args);
}
}
At this point, we can start the project to access , However, parameter filtering has not been performed yet , So if we input any parameter, it can be passed to Controller in , This is very unsafe in actual projects . In order to filter and clean up the data we input , You need a filter to do this .
Step eight : Create filters , Used to filter all request parameters submitted to the server
package com.xbmu.filter;
import com.xbmu.wrapper.XssRequestWrapper;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/* * Filter all request parameters submitted to the server */
public class XssFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
// Pass in the rewritten Request
filterChain.doFilter(new XssRequestWrapper(request),servletResponse);
}
}
Be careful : Through the above filter, we can find that we do not filter and clean the request parameters directly in the filter , It was a direct release , So how do we filter and clean up the request parameters ? In fact, the filtering and cleaning work is in another class XssRequestWrapper In the , When the above filter is released, you need to call filterChain.doFilter() Method , This method requires an incoming request Request object , At this point, we can put the current request Objects are packaged , and XssRequestWrapper Namely Request Object wrapper class , When the filter is released, the wrapper class will be called automatically getParameterValues Method , We can do it in the packaging class getParameterValues Method to filter and clean up the request parameters .
Step nine : establish XssRequestWrapper class
package com.xbmu.wrapper;
import org.owasp.validator.html.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class XssRequestWrapper extends HttpServletRequestWrapper {
/* * Policy file You need to put the policy file to be used under the project resource file path */
private static String antiSamyPath = XssRequestWrapper.class.getClassLoader()
.getResource("antisamy-test.xml").getFile();
public static Policy policy = null;
static {
// Specify the policy file
try {
policy = Policy.getInstance(antiSamyPath);
} catch (PolicyException e) {
e.printStackTrace();
}
}
/** * AntiSamy Filtering data * * @param taintedHTML Data to be filtered * @return Return filtered data */
private String xssClean(String taintedHTML) {
try {
// Use AntiSamy To filter
AntiSamy antiSamy = new AntiSamy();
CleanResults cr = antiSamy.scan(taintedHTML, policy);
taintedHTML = cr.getCleanHTML();
} catch (ScanException e) {
e.printStackTrace();
} catch (PolicyException e) {
e.printStackTrace();
}
return taintedHTML;
}
public XssRequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name);
if (values == null) {
return null;
}
int len = values.length;
String[] newArray = new String[len];
for (int j = 0; j < len; j++) {
System.out.println("Antisamy Filter cleaning , Clean up the previous parameter values :" + values[j]);
// Filter cleaning
newArray[j] = xssClean(values[j]);
System.out.println("Antisamy Filter cleaning , Parameter values after cleaning :" + newArray[j]);
}
return newArray;
}
}
Step 10 : To make the filter defined above effective , You need to create a configuration class , Used to initialize the filter object
package com.xbmu.config;
import com.xbmu.filter.XssFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AntiSamyConfiguration {
/** * Configure cross site attack filters */
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistration = new FilterRegistrationBean(new XssFilter());
filterRegistration.addUrlPatterns("/*");
filterRegistration.setOrder(1);
return filterRegistration;
}
}
Start project , Page input illegal data , You can see that the illegal data has been cleaned up .
Be careful : At present, when we filter the request parameters, we just wrap the class getParameterValues Methods are dealt with , In a real project, the data submitted by the user may be in the request header , It is also possible that the user submitted json data , So if you consider all the cases , We can clean up multiple methods in the wrapper class , as follows :
package com.xbmu.wrapper;
import org.owasp.validator.html.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.Map;
public class XssRequestWrapper extends HttpServletRequestWrapper {
/** * Policy file You need to put the policy file to be used under the project resource file path * */
private static String antiSamyPath = XssRequestWrapper.class.getClassLoader()
.getResource( "antisamy-test.xml").getFile();
public static Policy policy = null;
static {
// Specify the policy file
try {
policy = Policy.getInstance(antiSamyPath);
} catch (PolicyException e) {
e.printStackTrace();
}
}
/** * AntiSamy Filtering data * @param taintedHTML Data to be filtered * @return Return filtered data * */
private String xssClean( String taintedHTML){
try{
// Use AntiSamy To filter
AntiSamy antiSamy = new AntiSamy();
CleanResults cr = antiSamy.scan( taintedHTML, policy);
taintedHTML = cr.getCleanHTML();
}catch( ScanException e) {
e.printStackTrace();
}catch( PolicyException e) {
e.printStackTrace();
}
return taintedHTML;
}
public XssRequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public String[] getParameterValues(String name){
String[] values = super.getParameterValues(name);
if ( values == null){
return null;
}
int len = values.length;
String[] newArray = new String[len];
for (int j = 0; j < len; j++){
// Filter cleaning
newArray[j] = xssClean(values[j]);
}
return newArray;
}
@Override
public String getParameter(String paramString) {
String str = super.getParameter(paramString);
if (str == null) {
return null;
}
return xssClean(str);
}
@Override
public String getHeader(String paramString) {
String str = super.getHeader(paramString);
if (str == null) {
return null;
}
return xssClean(str);
}
@Override
public Map<String, String[]> getParameterMap() {
Map<String, String[]> requestMap = super.getParameterMap();
for (Map.Entry<String, String[]> me : requestMap.entrySet()) {
String[] values = me.getValue();
for (int i = 0; i < values.length; i++) {
values[i] = xssClean(values[i]);
}
}
return requestMap;
}
}

1.4、pd-tools-xss Use
pd-tools-xss The implementation of is consistent with the above introductory case , The bottom layer is also based on AntiSamy Verify and clean the input parameters , Make sure the input meets the application specification . For ease of use ,pd-tools-xss Has been defined as starter, Other applications only need to import their maven coordinate , It can be used without any additional configuration .
Specific use process :
First step : establish maven Project and configure pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/>
</parent>
<groupId>com.xbmu</groupId>
<artifactId>myXssApp</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.itheima</groupId>
<artifactId>pd-tools-xss</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
The second step : establish XSSController
package com.xbmu.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/xss")
public class XSSController {
@GetMapping("/get")
public String get(String text){
return " The processed text content is :" + text;
}
}
The third step : Create startup class
package com.xbmu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class XssApplication {
public static void main(String[] args) {
SpringApplication.run(XssApplication.class,args);
}
}
Start project , Visit the following address :

You can see , If you enter plain text, no processing will be done . If a special tag is entered, it is cleared .
边栏推荐
- Record the transfer of domain names from Alibaba cloud service providers to Huawei cloud
- ES6---4个强大运算符(??、??=、?.、?:)
- 大厂面试官:千万级数据量的表,如何进行快速查询?
- Please give an example of how to optimize MySQL index (sqlserver index optimization)
- Stm3 (cubeide) lighting experiment
- My heart's broken! After being cheated by 30000, a 16-year-old girl was unconvinced and cheated by 50000
- 一道golang中defer和函数结合的面试题
- Sqlx library usage
- Vivo official website app full model UI adaptation scheme
- cv图像翻转,EmguCV图像旋转「建议收藏」
猜你喜欢

Record the transfer of domain names from Alibaba cloud service providers to Huawei cloud

Oracle RAC RMAN backup error ora-19501 ora-15081

LeetCode刷题——猜数字大小II#375#Medium

The onnx model is exported as a TRT model

Zero basic learning canoe panel (17) -- panel CAPL function

JMeter distributed pressure measurement

Reading the pointpillar code of openpcdet -- Part 3: Calculation of loss function

Pychart automatically enters the test mode when running the program

Programmer's Guide to health quenching 5: introduction to sports Basics

MySQL master-slave configuration
随机推荐
Database SQL statement exercise "suggestions collection"
How to evaluate hardware resources (number of CPUs, memory size) when Oracle migrates from small computers to x86 architecture? Is there a measurement index or company?
cuda_ error_ out_ of_ Memory (out of memory)
YUV422 to RGB (422sp to 420p)
What's special about Huawei's innovative solutions to consolidate the foundation of ERP for small and medium-sized enterprises?
Leetcode skimming -- guess the size of numbers II 375 medium
Trusted and controllable way of Tencent cloud database
黑盒(功能)测试基本方法
Pycharm跑程序时自动进入测试模式
npm 模块 移除_【已解决】npm卸载模块后该模块并没有从package.json中去掉[通俗易懂]
919. 完全二叉树插入器 : 简单 BFS 运用题
How to solve the problem of high concurrency and large traffic with PHP
Rent two or three things
CNN structural design skills: taking into account speed accuracy and engineering implementation
How to copy all files in one folder to another folder
开源协议是否具有法律效力?
如何自动生成短链?如何在线批量生成带UTM参数的链接?
Test cases and defect report templates
Canvas fill gradient
DDD go practice