0
votes

I tried to code the script where to prevent cross-site scripting attacks by encoding HTML responses. but i have no idea how can i convert the characters before form submit??

html

<%
    String mobile       = common.setNullToString(request.getParameter("mobile"));
    String converted_param= detect_xss.escapeHtml(mobile); //convert method
%>

<form name="mainform" action="test2.jsp">
<input type="text" name="name" value="" >
<input type="button" onclick="button();">
</form>

java file

public class detect_xss {
    public static final HashMap m = new HashMap();
    static{
     m.put(34, "&quot;"); // < - less-than
     m.put(60, "&lt;"); // < - less-than
     m.put(62, "&gt;"); // > - greater-thanof entities and integer value of a char
    }

     public static String escapeHtml(String html) 
     {
         String str = html;
         try 
         {
             StringWriter writer = new StringWriter((int)(str.length() * 1.5));
             escape(writer, str);
             return writer.toString();
         }
         catch (IOException ioe) 
         {
             ioe.printStackTrace();
             return null;
         }
    }

     public static void escape(Writer writer, String str) throws IOException 
     {
         int len = str.length();
         for (int i = 0; i < len; i++) 
         {
             char c = str.charAt(i);
             int ascii = (int) c;
             String entityName = (String) m.get(ascii);
             if (entityName == null) 
             {
                 if (c > 0x7F) 
                 {
                    writer.write("&#");
                    writer.write(Integer.toString(c, 10));
                    writer.write(';');
                 }
                 else {
                     writer.write(c);
                 }
             } else {
                 writer.write(entityName);
             }
         }
     }

}

input text entered value = "< script >alert("test")< /script>"

http://localhost:9080/home/test2.jsp?mobile=<script>alert%28"test"%29<%2Fscript>

expected result

http://localhost:9080/amgeneral/test2.jsp?mobile=&lt;script&gt;alert(&quot;test&quot;)&lt;/script&gt;
1

1 Answers

0
votes

Encoding html responses is not proper way to prevent CSRF attack.If you do not want to write CSRF protection, use OWASP CSRF Guard.This is a filter and can integrate with your jsp project. The other option is you can wirte manually CSRF control by yourself.Check this link.