지 못하게 하는 방법은 무엇입니까 사람들이 하기에서 XSS in Spring MVC?
-
23-09-2019 - |
문제
나는 무엇을 해야 하는지 XSS in Spring MVC?바로 지금 나는 그 모든 장소가 출력 사용자가 텍스트로 JSTL <c:out>
태그 fn:escapeXml()
기능,그러나 이것은 오류가 발생하기 쉬운로 놓칠 수도 있습니다.
가 쉽게 체계적인 방법으로 이를 방지하기 위해?어쩌면 다음과 같 필터 또는 뭔가?내가 수집하는 입력에 의해 지정 @RequestParam
매개 변수 내에서 컨트롤러 방법이 있습니다.
해결책
임계 값은 여기에서 문제가되지 않아야합니다. CA에서 가치를 변경했고 예외가 발생하지 않는 것 같습니다. SPFolder는 모든 것을 재귀 적으로 반환하지 않고 많은 불특정 Spectem을 덤프합니다. SPFolder를 사용하여 ProcessFilesInFolder로 ContentIterator를 사용하는 것이 좋습니다. http://www.askaboutasp.net/_-_105_what_is_the_best_way_to_itrate_through_a_sharepoint_2010_folder_recur.aspx
다른 팁
Try XSSFilter.
I use Hibernate Validator via @Valid
for all input objects (binding and @RequestBody
json, see https://dzone.com/articles/spring-31-valid-requestbody). So @org.hibernate.validator.constraints.SafeHtml
is a good solution for me.
Hibernate SafeHtmlValidator
depends on org.jsoup
, so it's needed to add one more project dependencies:
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.1</version>
</dependency>
For bean User
with field
@NotEmpty
@SafeHtml
protected String name;
for update attempt with value <script>alert(123)</script>
in controller
@PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
public void update(@Valid @RequestBody User user, @PathVariable("id") int id)
or
@PostMapping
public void createOrUpdate(@Valid User user) {
is thrown BindException
for binding and MethodArgumentNotValidException
for @RequestBody
with default message:
name may have unsafe html content
Validator works as well for binding, as before persisting. Apps could be tested at http://topjava.herokuapp.com/
When you are trying to prevent XSS, it's important to think of the context. As an example how and what to escape is very different if you are ouputting data inside a variable in a javascript snippet as opposed to outputting data in an HTML tag or an HTML attribute.
I have an example of this here: http://erlend.oftedal.no/blog/?blogid=91
Also checkout the OWASP XSS Prevention Cheat Sheet: http://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet
So the short answer is, make sure you escape output like suggested by Tendayi Mawushe, but take special care when you are outputting data in HTML attributes or javascript.
How are you collecting user input in the first place? This question / answer may assist if you're using a FormController
:
항상 확인할 수동으로 이 방법을 사용하는 태그는지 확인하고 그들은 항상 탈출(번)습니다.프레임워크가 많은 버그와에서 이 측면이다.
Instead of relying only on <c:out />
, an antixss library should also be used, which will not only encode but also sanitize malicious script in input. One of the best library available is OWASP Antisamy, it's highly flexible and can be configured(using xml policy files) as per requirement.
For e.g. if an application supports only text input then most generic policy file provided by OWASP can be used which sanitizes and removes most of the html tags. Similarly if application support html editors(such as tinymce) which need all kind of html tags, a more flexible policy can be use such as ebay policy file
**To avoid XSS security threat in spring application**
solution to the XSS issue is to filter all the textfields in the form at the time of submitting the form.
It needs XML entry in the web.xml file & two simple classes.
java code :-
The code for the first class named CrossScriptingFilter.java is :
package com.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
public class CrossScriptingFilter implements Filter {
private static Logger logger = Logger.getLogger(CrossScriptingFilter.class);
private FilterConfig filterConfig;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
logger.info("Inlter CrossScriptingFilter ...............");
chain.doFilter(new RequestWrapper((HttpServletRequest) request), response);
logger.info("Outlter CrossScriptingFilter ...............");
}
}
The code second class named RequestWrapper.java is :
package com.filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.log4j.Logger;
public final class RequestWrapper extends HttpServletRequestWrapper {
private static Logger logger = Logger.getLogger(RequestWrapper.class);
public RequestWrapper(HttpServletRequest servletRequest) {
super(servletRequest);
}
public String[] getParameterValues(String parameter) {
logger.info("InarameterValues .. parameter .......");
String[] values = super.getParameterValues(parameter);
if (values == null) {
return null;
}
int count = values.length;
String[] encodedValues = new String[count];
for (int i = 0; i < count; i++) {
encodedValues[i] = cleanXSS(values[i]);
}
return encodedValues;
}
public String getParameter(String parameter) {
logger.info("Inarameter .. parameter .......");
String value = super.getParameter(parameter);
if (value == null) {
return null;
}
logger.info("Inarameter RequestWrapper ........ value .......");
return cleanXSS(value);
}
public String getHeader(String name) {
logger.info("Ineader .. parameter .......");
String value = super.getHeader(name);
if (value == null)
return null;
logger.info("Ineader RequestWrapper ........... value ....");
return cleanXSS(value);
}
private String cleanXSS(String value) {
// You'll need to remove the spaces from the html entities below
logger.info("InnXSS RequestWrapper ..............." + value);
//value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
//value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
//value = value.replaceAll("'", "& #39;");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
value = value.replaceAll("(?i)<script.*?>.*?<script.*?>", "");
value = value.replaceAll("(?i)<script.*?>.*?</script.*?>", "");
value = value.replaceAll("(?i)<.*?javascript:.*?>.*?</.*?>", "");
value = value.replaceAll("(?i)<.*?\\s+on.*?>.*?</.*?>", "");
//value = value.replaceAll("<script>", "");
//value = value.replaceAll("</script>", "");
logger.info("OutnXSS RequestWrapper ........ value ......." + value);
return value;
}
The only thing remained is the XML entry in the web.xml file:
<filter>
<filter-name>XSS</filter-name>
<display-name>XSS</display-name>
<description></description>
<filter-class>com.filter.CrossScriptingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>XSS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The /* indicates that for every request made from browser, it will call CrossScriptingFilter class. Which will parse all the components/elements came from the request & will replace all the javascript tags put by hacker with empty string i.e