Java解決xss轉(zhuǎn)義導致轉(zhuǎn)碼的問題
一、xss簡介
人們經(jīng)常將跨站腳本攻擊(Cross Site Scripting)縮寫為CSS,但這會與層疊樣式表(Cascading Style Sheets,CSS)的縮寫混淆。因此,有人將跨站腳本攻擊縮寫為XSS??缯灸_本攻擊(XSS),是最普遍的Web應用安全漏洞。這類漏洞能夠使得攻擊者嵌入惡意腳本代碼到正常用戶會訪問到的頁面中,當正常用戶訪問該頁面時,則可導致嵌入的惡意腳本代碼的執(zhí)行,從而達到惡意攻擊用戶的目的。
攻擊者可以使用戶在瀏覽器中執(zhí)行其預定義的惡意腳本,其導致的危害可想而知,如劫持用戶會話,插入惡意內(nèi)容、重定向用戶、使用惡意軟件劫持用戶瀏覽器、繁殖XSS蠕蟲,甚至破壞網(wǎng)站、修改路由器配置信息等。
二、解決方式
解決方式有很多,這里介紹將內(nèi)容經(jīng)過轉(zhuǎn)義然后再存儲到服務器上。
package com.wssnail.xss.config;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.io.IOException;
import java.util.List;
import java.util.ListIterator;
/**
* @author 熟透的蝸牛
* @version 1.0
* @description: 配置xss攻擊過濾
* @date 2023/8/14 23:48
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
/**
* 替換默認的MappingJackson2HttpMessageConverter,過濾(json請求參數(shù))xss
*/
ListIterator<HttpMessageConverter<?>> listIterator = messageConverters.listIterator();
while (listIterator.hasNext()) {
HttpMessageConverter<?> next = listIterator.next();
if (next instanceof MappingJackson2HttpMessageConverter) {
listIterator.remove();
break;
}
}
messageConverters.add(getMappingJackson2HttpMessageConverter());
}
public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
// 創(chuàng)建自定義ObjectMapper
SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, new JsonHtmlXssDeserializer(String.class));
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().applicationContext(this.getApplicationContext()).build();
objectMapper.registerModule(module);
// 創(chuàng)建自定義消息轉(zhuǎn)換器
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
return mappingJackson2HttpMessageConverter;
}
/**
* 添加默認請求類型
*/
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.ignoreAcceptHeader(true).
defaultContentType(MediaType.APPLICATION_JSON, MediaType.TEXT_XML, MediaType.APPLICATION_XML);
}
}
/**
* @author 熟透的蝸牛
* @version 1.0
* @description: 對xss進行過濾
* @date 2023/8/14 23:49
*/
class JsonHtmlXssDeserializer extends JsonDeserializer<String> {
public JsonHtmlXssDeserializer(Class<String> string) {
super();
}
@Override
public Class<String> handledType() {
return String.class;
}
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException {
String value = jsonParser.getValueAsString();
if (!StringUtils.isEmpty(value)) {
return StringEscapeUtils.escapeHtml4(value);
}
return value;
}
}
請求如上接口,經(jīng)過轉(zhuǎn)義之后,存到數(shù)據(jù)庫的內(nèi)容就不再是我們傳參的數(shù)據(jù),而是經(jīng)過轉(zhuǎn)義的內(nèi)容

經(jīng)過查詢之后內(nèi)容就回顯成轉(zhuǎn)義之后的內(nèi)容了,如下圖

三、解決轉(zhuǎn)義的內(nèi)容
先說一下思路,自定義一個注解,作用在實體類或者字段上,當查詢的時候,在數(shù)據(jù)返回之前,對數(shù)據(jù)進行反轉(zhuǎn)義。下面直接上代碼。
自定義注解
package com.wssnail.xss.annotation;
import java.lang.annotation.*;
@Target({ElementType.TYPE,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface StringEscapeCode {
}工具類
package com.wssnail.xss.utils;
import com.wssnail.xss.annotation.StringEscapeCode;
import org.apache.commons.text.StringEscapeUtils;
import java.lang.reflect.Field;
/**
* @author 熟透的蝸牛
* @version 1.0
* @description: 配置字符串格式文本處理工具
* @date 2023/8/14 23:50
*/
public class StringEscapeCodeUtil {
public static void stringEscape(Class<?> clazz, Object obj) throws IllegalAccessException {
StringEscapeCode declaredAnnotation = clazz.getDeclaredAnnotation(StringEscapeCode.class);
if (declaredAnnotation != null) {
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
if (fields[i].getGenericType().toString().endsWith("String")) {
//有注解,設置字段
fields[i].setAccessible(true);
String value = StringEscapeUtils.unescapeHtml4((String) fields[i].get(obj));
fields[i].set(obj, value);
}
}
} else {
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
StringEscapeCode annotation = fields[i].getAnnotation(StringEscapeCode.class);
if (fields[i].getGenericType().toString().endsWith("String")) {
if (annotation != null) {
//有注解,設置字段
fields[i].setAccessible(true);
String value = StringEscapeUtils.unescapeHtml4((String) fields[i].get(obj));
fields[i].set(obj, value);
}
}
}
}
}
}實際使用
package com.wssnail.xss.annotation;
import java.lang.annotation.*;
/**
* @author 熟透的蝸牛
* @version 1.0
* @description: 自定義注解
* 使用方法 將該注解添加到類上,或者屬性上,只有作用在、string類型的屬性上,注解才會生效
* @date 2023/8/15 0:13
*/
@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface StringEscapeCode {
} public User getById(Integer id) {
try {
User user = userMapper.findByID(id);
Class<? extends User> clazz = user.getClass();
StringEscapeCodeUtil.unStringEscape(clazz, user);
return user;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}然后查詢的時候,就會正常顯示內(nèi)容了。

完整代碼 xss-demo: 解決xss轉(zhuǎn)義亂碼返回的問題
到此這篇關于Java解決xss轉(zhuǎn)義導致轉(zhuǎn)碼的問題的文章就介紹到這了,更多相關Java xss轉(zhuǎn)義內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
IntelliJ IDEA中新建Java class的解決方案
今天小編就為大家分享一篇關于IntelliJ IDEA中新建Java class的解決方案,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-10-10
解決Maven parent.relativePath帶給我的坑
在Linux環(huán)境下使用Maven進行項目打包時,可能會遇到“當前目錄沒有pom文件”的錯誤,需要確認在包含pom.xml文件的項目目錄下執(zhí)行Maven命令,另外,如果遇到“parent.relativePath points at wrong local POM”錯誤,可能是父模塊依賴問題2024-09-09

