net.dreamlu.mica.xss.core.DefaultXssCleaner Maven / Gradle / Ivy
Show all versions of mica-xss Show documentation
/*
* Copyright (c) 2019-2029, Dreamlu 卢春梦 ([email protected] & www.dreamlu.net).
*
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/lgpl.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.dreamlu.mica.xss.core;
import net.dreamlu.mica.xss.config.MicaXssProperties;
import net.dreamlu.mica.xss.config.MicaXssProperties.Mode;
import net.dreamlu.mica.xss.utils.XssUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Entities;
import org.springframework.util.StringUtils;
import org.springframework.web.util.HtmlUtils;
import java.nio.charset.StandardCharsets;
/**
* 默认的 xss 清理器
*
* @author L.cm
*/
public class DefaultXssCleaner implements XssCleaner {
private final MicaXssProperties properties;
public DefaultXssCleaner(MicaXssProperties properties) {
this.properties = properties;
}
private static Document.OutputSettings getOutputSettings(MicaXssProperties properties) {
return new Document.OutputSettings()
// 2. 转义,没找到关闭的方法,目前这个规则最少
.escapeMode(Entities.EscapeMode.xhtml)
// 3. 保留换行
.prettyPrint(properties.isPrettyPrint());
}
@Override
public String clean(String name, String bodyHtml, XssType type) {
// 1. 为空直接返回
if (!StringUtils.hasText(bodyHtml)) {
return bodyHtml;
}
Mode mode = properties.getMode();
if (Mode.ESCAPE == mode) {
// html 转义
return HtmlUtils.htmlEscape(bodyHtml, StandardCharsets.UTF_8.name());
} else if (Mode.VALIDATE == mode) {
// 校验
if (Jsoup.isValid(bodyHtml, XssUtil.WHITE_LIST)) {
return bodyHtml;
}
throw type.getXssException(name, bodyHtml, "Xss validate fail, input value:" + bodyHtml);
} else {
// 4. 清理后的 html
String escapedHtml = Jsoup.clean(bodyHtml, "", XssUtil.WHITE_LIST, getOutputSettings(properties));
if (properties.isEnableEscape()) {
return escapedHtml;
}
// 5. 反转义
return Entities.unescape(escapedHtml);
}
}
}