Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure Spring Controller and/or JAXB to help prevent SQL / XSS injection

I have a Controller in Spring with a method like the following

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

I want to be sure that the Request Body does not contain any SQL or Javascript characters to help avoid SQL Injection, XSS attacks etc.

Does JAXB already handle that scenario? I was considering writing a filter but I can only read the request body once?

Any suggestions?

like image 543
kellyfj Avatar asked May 06 '13 19:05

kellyfj


People also ask

Does spring prevent SQL injection?

In general, in most cases, preventing a Java SQL injection is the same as preventing a Spring Boot SQL injection. As stated above, an SQL injection is basically an attack that incorporates special control characters into a valid input for malicious intents.


1 Answers

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)}
like image 56
sehrope Avatar answered Oct 11 '22 09:10

sehrope