jaksdfjl
jaksdfjl

Reputation: 125

AntiSamy to prevent XSS in java?

Basically I have a web-app which it currently is vulnerable to XSS. Based on my research I found one of good and open library that can help would be AntiSamy. So I downloaded the library .jar file which is antisamy-1.5.1.jar and The policy file antisamy-slashdot-1.4.4.xml and exported it to my project WEB-INF directory.

I'm pretty much new to AntiSamy and don't really know how to implement it on a string to encode and secure it from XSS.

Say I've a string of: String XSSPossible = "<script>alert("It's vulnerable.");</script>"; Now I want to encode this to a normal text and secure it from XSS.

Much Regards.

Upvotes: 5

Views: 7898

Answers (1)

Hitesh Ghuge
Hitesh Ghuge

Reputation: 823

You can use below code

public class AntisamySample 
{
     public static AntiSamy antiSamy; 
     public static Policy policy; 
     public static CleanResults cleanResults; 
     static String policyFileName = "antisamy-slashdot-1.4.4.xml"; 

     private Policy gtePolicyFile()
     {
         try
         {
             policy = policy.getInstance(this.getClass().getResourceAsStream(policyFileName));
         }
         catch (PolicyException e) 
         {
            e.printStackTrace();
         }
         return policy;
     }

     public static void main(String[] args) 
     {
         String XSSPossible = "<script>alert('It's vulnerable.');</script>";
         String cleanResult = "";
         try
         { 
             AntisamySample  antisamy = new AntisamySample();
             antiSamy = new AntiSamy();
             policy = antisamy.gtePolicyFile();
             cleanResults = antiSamy.scan(XSSPossible, policy); 

             cleanResult = cleanResults.getCleanHTML(); 
         } 
         catch(PolicyException e) 
         { 
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
         catch (ScanException e)
         {
             // TODO Auto-generated catch block
             e.printStackTrace();
         } 
     }
}

This will return you clean HTML

All the rules to get clean HTML are in antisamy*.xml file. There are four different policy files.

As per your requirements you can use any policy file and add rules as per your requirements.

Here is the more details about antisamy

Upvotes: 1

Related Questions