如何使用过滤器执行输出编码以防止XSS? [英] How to perform output encoding using filter to prevent XSS?
问题描述
我在servlet中使用以下代码:
I am using the following code in servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("<html>");
out.println("<body>");
out.println("<script>alert(1)</script>");
out.println("</body>");
out.println("</html>");
}
以下代码:
public class SampleFilter implements Filter {
protected FilterConfig config;
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws ServletException, IOException {
long startTime = System.currentTimeMillis();
ServletResponse newResponse = response;
if (request instanceof HttpServletRequest) {
System.out.println("in filter if1");
newResponse = new CharResponseWrapper((HttpServletResponse) response);
}
System.out.println("after filter if1");
chain.doFilter(request, newResponse);
long elapsed = System.currentTimeMillis() - startTime;
if (newResponse instanceof CharResponseWrapper) {
System.out.println("in filter if2");
String text = newResponse.toString();
if (text != null) {
text = SampleFilter.HTMLEntityEncode(text);//.toUpperCase();
response.getWriter().write(text);
}
}
System.out.println("after filter if2");
config.getServletContext().log(" took " + elapsed + " ms");
System.out.println(elapsed);
}
private static String HTMLEntityEncode(String input) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (Character.isLetterOrDigit(ch) || Character.isWhitespace(ch)) {
sb.append(ch);
} else {
sb.append("&#" + (int)ch + ";");
}
}
return sb.toString();
}
}
我想在浏览器中获得以下显示数据:
I want to get the following display data in the browser:
<script>alert(1)</script>
而不是我得到
<html>
<body>
<script>alert(1)</script>
</body>
</html>
。
任何帮助会很棒。
推荐答案
不要这么做。只需使用 JSP 生成HTML输出即可。 JSP标准标记库( JSTL )提供内置方法,可以从<$ $的XSS攻击漏洞中逃避用户控制的数据c $ c>< c:out> 标签和 $ {fn:escapeXml()}
功能..
Don't do it the hard way. Just use JSP for generating HTML output. The JSP standard tag library (JSTL) offers builtin ways to escape user-controlled data from XSS attack holes in flavor of <c:out>
tag and ${fn:escapeXml()}
function..
<p>Welcome, <c:out value="${user.name}" />!</p>
...
<input type="text" name="foo" value="${fn:escapeXml(param.foo)}" />
他们将逃脱预先确定的XML实体,如<
,& gt;
使它变得完全无害。
They will escape predefinied XML entities like <
by >
so that it becomes totally harmless.
Servlets 不是旨在生成HTML输出。它们的设计目的是控制请求/响应。
Servlets are not designed for generating HTML output. They're designed with the purpose to control the request/response.
- XSS prevention in JSP/Servlet web application
这篇关于如何使用过滤器执行输出编码以防止XSS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!