Java解決xss轉義導致轉碼的問題
一、xss簡介
人們經(jīng)常將跨站腳本攻擊(Cross Site Scripting)縮寫為CSS,但這會與層疊樣式表(Cascading Style Sheets,CSS)的縮寫混淆。因此,有人將跨站腳本攻擊縮寫為XSS??缯灸_本攻擊(XSS),是最普遍的Web應用安全漏洞。這類漏洞能夠使得攻擊者嵌入惡意腳本代碼到正常用戶會訪問到的頁面中,當正常用戶訪問該頁面時,則可導致嵌入的惡意腳本代碼的執(zhí)行,從而達到惡意攻擊用戶的目的。
攻擊者可以使用戶在瀏覽器中執(zhí)行其預定義的惡意腳本,其導致的危害可想而知,如劫持用戶會話,插入惡意內容、重定向用戶、使用惡意軟件劫持用戶瀏覽器、繁殖XSS蠕蟲,甚至破壞網(wǎng)站、修改路由器配置信息等。
二、解決方式
解決方式有很多,這里介紹將內容經(jīng)過轉義然后再存儲到服務器上。
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)建自定義消息轉換器
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)過轉義之后,存到數(shù)據(jù)庫的內容就不再是我們傳參的數(shù)據(jù),而是經(jīng)過轉義的內容

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

三、解決轉義的內容
先說一下思路,自定義一個注解,作用在實體類或者字段上,當查詢的時候,在數(shù)據(jù)返回之前,對數(shù)據(jù)進行反轉義。下面直接上代碼。
自定義注解
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);
}
}然后查詢的時候,就會正常顯示內容了。

到此這篇關于Java解決xss轉義導致轉碼的問題的文章就介紹到這了,更多相關Java xss轉義內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Mybatis-Plus進階分頁與樂觀鎖插件及通用枚舉和多數(shù)據(jù)源詳解
這篇文章主要介紹了Mybatis-Plus的分頁插件與樂觀鎖插件還有通用枚舉和多數(shù)據(jù)源的相關介紹,文中代碼附有詳細的注釋,感興趣的朋友來看看吧2022-03-03
SpringCloud 服務負載均衡和調用 Ribbon、OpenFeign的方法
這篇文章主要介紹了SpringCloud 服務負載均衡和調用 Ribbon、OpenFeign的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09

