6

我在 Spring 中有一个控制器,其方法如下

@RequestMapping(value = "/v1/something", method = RequestMethod.POST, headers = "content-type=application/xml")
@Valid
public void something(@RequestBody final SomeBody myDto  . . . . .

我想确保请求正文不包含任何 SQL 或 Javascript 字符,以帮助避免 SQL 注入、XSS 攻击等。

JAXB 是否已经处理了这种情况?我正在考虑编写一个过滤器,但我只能读取一次请求正文?

有什么建议么?

4

3 回答 3

5

Proper XSS and SQL injection protection (and data validation in general) can only happen on the server side. Client side validation is irrelevant as a malicious user can just write their own client or send custom HTTP request. Client side validation is only useful to notify non-malicious users of form validations without a server round trip (ex: verify that a field is a number or email address). Even in that situation the server must also perform the validation.

To prevent SQL injection use bind variables (eg prepared statements) for all parameterized queries. You should never have to concatenate client inputs to generate a SQL statement. If you never generate SQL statements from client input and only use them as bind variables you don't have to worry about SQL injection at all.

String clientValue = ...
Connection conn = ...
PreparedStatement stmt = conn.prepare("INSERT INTO foobar VALUES (?)");
stmt.setString(clientValue);
stmt.executeUpdate();

Or with Spring JDBC:

String clientValue = ...
JdbcTemplate jdbcTemplate = ...
jdbcTemplate.update("INSERT INTO foobar VALUES (?)", clientValue);

To prevent XSS make sure to sanitize all data before you output it. White-listing client data when it is saved is generally a good idea too if you have an explicit subset of acceptable text but it becomes more complicated when you factor in Unicode support. It's generally much easier to just deal with it on the rendering side.

For example if you are using JSTL to render your output you would use something like:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
${fn:escapeXml(myModelVariable)}
于 2013-05-15T08:46:59.193 回答
3

您可以使用Filters来清洁您的表格。它将获取您所有的请求属性并将它们全部清除。另一种选择是使用JSoupAPI。访问以下链接以了解更多信息。

JSoup XSS API 的

过滤器方法来防止 XSS 威胁

编辑 :

阅读 OWASP 表以了解如何避免 XSS 和 SQL 注入。

OWASP - 预防 XSS

OWASP - 防止 SQL 注入

看看与 spring 3.1 集成的HDIV,它对 XSS、CSRF、数据完整性检查具有开箱即用的支持。

于 2013-05-09T05:09:47.233 回答
1

For XSS attacks are mostly client side hack.For every user input you can actually sanitize the input data using encoding so that it takes out all the special characters. The basic way to handle on client side is to use the Javascript escape() function. OWASP is a good refernce to go thru the lon list of client side hacks. For Server side hacks to prevent SQL injection you can look at using Prepared statements or using template based query creation (QueryDSL) or HQL etc.

于 2013-05-14T09:26:53.670 回答