views:

248

answers:

1

Hello colleagues!

Googling today I couldn't found sample or mentioning of best practice: how to escape user input in Struts2. Of course I can manually convert characters on validate() method, but it looks too obvious. So may be exists some automation to avoid code/script injection?

A: 

There's the basic feature/good practice: the property tag by default escapes html special chars, so as long as you keep that filtering (see the 'escape' and 'escapeJavascript' attributes), you are quite safe -in that respect.

For a more general case of checking all user input in your webapp (which, in theory, you could do extending the param interceptor or making up another interceptor or filter), it's rarely possible to establish some general rule (which characters/patterns are prohibited?) and what to do (silently erasing them or throw some validation error/warning?).

Perhaps you are thinking of more particular case of user inputs which are to be displayed in a web page (typically user comments) and which could accept a restricted set of html tags. In that case, I'd deal with those fields in particular, perhaps by writing some utility sanitizer code and plugging it in the corresponding setters or getters. A more sophisticated solution would be to define your own class (say UserComment) for those fields - the class would basically wrap a String, and then I'd write a corresponding Type Converter that takes responsability for the sanitization. Again, you must decide what action to take in the case of prohibited characters/tags.

leonbloy