1

Before you immediately comment "you can't trust the client!", please read the whole question.

I've been reading about how to prevent XSS attacks lately, and everything I've found says that the server should sanitize the data that will be put into the webpage. This would basically look like addToDatabase(filter(userResponse)). Then the client can safely add display anything that it gets from the server.

I was wondering if it would be safe to store the potentially unsafe data in the server, and have the client filter it when it was received, like addHTML(filter(serverResponse)). This would stop the data from being executed client-side, so no XSS would take place. I understand that anyone could simply remove that filter, however all that would do is make themselves vulnerable. Since other clients would filter anything sent to them, a malicious client could could only disable their own filter and mess up themselves. (I'm not talking about SQL injection prevention, that would be obviously have to be server-side)

To summarize: The server doesn't sanitize, but the clients sanitize whatever they receive.

Would this be safe?

2 Answers 2

2

The answer is at the point where you're generating HTML, is where HTML encoding/sanitizing should occur.

If server side code is generating the HTML then it should be server side. If client side is generating HTML then it should be client side.

In other words if server side is generating JSON to send to the client then server should be JSON encoding the data, but not prematurely HTML encode.

1

Yes. BUT.

The data is getting filtered either way. And assuming filter() runs the same algorithm the result would be the same (ignoring any effects of charsets in database etc and that you catch all errors). However, you increase the likelihood of making a mistake in future. If you have a workflow that all user inputs are sanitised before being stored, then the DB only stores sanitised inputs, and can be outputted straight to the client. If instead you store unsanitised input, then any time the data is outputted if a programmer doesn't remember to pass it through the filter then XSS (etc) would be possible.

It might work for the specific example you have in mind but in general it's not a good idea, and it might make your life harder in future.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .