Alex Rivera | Logout

Ways to prevent SQL Injection Attack & XSS in Java Web Application

Asked 2009-01-27T20:12:16.850
12

I'm writing a java class which would be invoked by a servlet filter and which checks for injection attack attempts and XSS for a java web application based on Struts. The InjectionAttackChecker class uses regex & java.util.regex.Pattern class to validate the input against the patterns specified in regex.

With that said, I have following questions:

  1. What all special characters and character patterns (for example <>, ., --, <=, ==,>=) should be blocked so that injection attack could be prevented.
  2. Is there any existing regex pattern which I could use as is?
  3. I have to allow some of the special character patterns in some specific cases, some example values (to be allowed) are (used 'pipe' | character as a separator of different values) *Atlanta | #654,BLDG 8 #501 | Herpes simplex: chronic ulcer(s) (>1 mo. duration) or bronchitis, pneumonitis, or esophagitis | FUNC & COMP(date_cmp), "NDI & MALKP & HARS_IN(icd10, yes)" . What strategy should I adopt so that injection attack and XSS could be prevented but still allowing these character patterns.

I hope I have mentioned the question clearly. But if I didn't, I apologize as its just my 2nd question. Please let me know if any clarification is needed.

Edit
Report

1 Answer

1

don't filter or block values.

  1. you should ensure that when combining bits of text you do the proper type conversions :) ie: if you have a piece a string which is type HTML and a string which is type TEXT you should convert TEXT to HTML instead of blindly concatenating them. in haskell you can conveniently enforce this with the type system.

good html templating languages will escape by default. if you are generating XML/HTML then sometimes it is better to use DOM tools than a templating language. if you use a DOM tool then it removes a lot of these issues. unfortunately, DOM tool is usually crap compared to templating :)

  1. if you take strings of type HTML from users you should sanitize it with a library to remove all not-good tags/attributes. there are lots of good whitelist html filters out there.
  2. you should always use parameterized queries. ALWAYS! if you have to build up queries dynamically then build them up dynamically with parameters. don't ever combine non-SQL typed strings with SQL typed strings.
answered 2009-03-11T17:47:56.570

Your Answer