XSS prevention in JSP/Servlet web application

前端 未结 9 1354
自闭症患者
自闭症患者 2020-11-21 13:55

How can I prevent XSS attacks in a JSP/Servlet web application?

相关标签:
9条回答
  • 2020-11-21 14:29

    I had great luck with OWASP Anti-Samy and an AspectJ advisor on all my Spring Controllers that blocks XSS from getting in.

    public class UserInputSanitizer {
    
        private static Policy policy;
        private static AntiSamy antiSamy;
    
        private static AntiSamy getAntiSamy() throws PolicyException  {
            if (antiSamy == null) {
                policy = getPolicy("evocatus-default");
                antiSamy = new AntiSamy();
            }
            return antiSamy;
    
        }
    
        public static String sanitize(String input) {
            CleanResults cr;
            try {
                cr = getAntiSamy().scan(input, policy);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return cr.getCleanHTML();
        }
    
        private static Policy getPolicy(String name) throws PolicyException {
            Policy policy = 
                Policy.getInstance(Policy.class.getResourceAsStream("/META-INF/antisamy/" + name + ".xml"));
            return policy;
        }
    
    }
    

    You can get the AspectJ advisor from the this stackoverflow post

    I think this is a better approach then c:out particular if you do a lot of javascript.

    0 讨论(0)
  • 2020-11-21 14:32

    The how-to-prevent-xss has been asked several times. You will find a lot of information in StackOverflow. Also, OWASP website has an XSS prevention cheat sheet that you should go through.

    On the libraries to use, OWASP's ESAPI library has a java flavour. You should try that out. Besides that, every framework that you use has some protection against XSS. Again, OWASP website has information on most popular frameworks, so I would recommend going through their site.

    0 讨论(0)
  • 2020-11-21 14:32

    I would suggest regularly testing for vulnerabilities using an automated tool, and fixing whatever it finds. It's a lot easier to suggest a library to help with a specific vulnerability then for all XSS attacks in general.

    Skipfish is an open source tool from Google that I've been investigating: it finds quite a lot of stuff, and seems worth using.

    0 讨论(0)
提交回复
热议问题