Monday, 9 April 2012

Secure your web apps with HDIV


Recently integrated hdiv framework into the web application I am working on.

We had already had taken enough safety measures to secure the web application, like

1. Always encoding the outputs (like always output from jsp using <C:out> with xml encoding instead of just printing them)
2. Code to secure against SQL injections
3. etc. 

But HDIV is an interesting framework, it seamlessly integrates with the existing application, no need to change the existing code (most of the time) and secures web application mainly against following attacks.

1. Cross site Scripting
2. SQL Injections
3. URL Tampering (I really like this protection, IMO only the links in the web site should be used for navigation, user should not be able to change the URL, especially the values in the path to navigate)
4. Spring bean auto binding, etc.

There are good documents about HDIV in its website hdiv.org, but did found much documentation about its integration with existing applications. So decided to explore my self and found an interesting example implementation at https://github.com/hdiv/hdiv-spring-mvc-showcase, downloaded that and explored, it is really awesome. So I am documenting some simple steps to integrate hdiv with your existing spring application.

Step 1: Dependencies

Include following dependencies in your project, for maven,

        <dependency>
                 <groupId>org.hdiv</groupId>
                   <artifactId>hdiv-core</artifactId>
                   <version>2.1.1</version>
          </dependency>
          <dependency>
                   <groupId>org.hdiv</groupId>
               <artifactId>hdiv-config</artifactId>
               <version>2.1.1</version>
          </dependency>
          <dependency>
                   <groupId>org.hdiv</groupId>
                   <artifactId>hdiv-spring-mvc</artifactId>
                   <version>2.1.1</version>
          </dependency>
          <dependency>
                   <groupId>org.hdiv</groupId>
                <artifactId>hdiv-jstl-taglibs-1.2</artifactId>
                 <version>2.1.1</version>
         </dependency>

Step 2: HDIV-Config.xml

Copy hdiv-config.xml to your resource folder(alternatively classpath, sample found in the showcase app)
see details about hdiv-config at bottom of this post.

Step 3:  web.xml Changes
Step 3.1

Include hdiv-config.xml in context config location as

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
               classpath:/spring-context.xml
               classpath:/hdiv-config.xml
        </param-value>
    </context-param>

Step 3.2

include following hdiv specific entries as,

    <!-- HDIV Init Listener -->
    <listener>
        <listener-class>org.hdiv.listener.InitListener</listener-class>
    </listener>
    <!-- HDIV Validator Filter -->
    <filter>
        <filter-name>ValidatorFilter</filter-name>
        <filter-class>org.hdiv.filter.ValidatorFilter</filter-class>
     </filter>
     <filter-mapping>
        <filter-name>ValidatorFilter</filter-name>
        <servlet-name>dispatcher</servlet-name>
     </filter-mapping>

here dispatcher is the nothing but spring dispatcher servlet, example

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>

Step 3.3

 point JSTL to hdiv customized JSTL tag library.

    <jsp-config>
        <taglib>
           <taglib-uri>http://java.sun.com/jsp/jstl/core</taglib-uri>
           <taglib-location>/WEB-INF/tlds/hdiv-c.tld</taglib-location>
        </taglib>
    </jsp-config>                    


Step 4: copy hdiv-c.tld to web-inf

copy the hdiv-c.tld from sample app to web-inf/tlds folder

Step 5: Create your initial landing page

HDIV protected site always expects an HDIV state code to validate the page, if you are trying to access any page without hdiv state it will redirect you to the error page, so we have to create some initial landing page which redirect to other page with hdiv state, following is an sample jsp for initial landing page

name: index.jsp

<body>
        <c:redirect url="login/login.html"></c:redirect>
</body> 
</html> 

include this file in welcome pages list in web.xml and place it in the root folder and add the root folder as starting pages folder in hdiv-config.xml, example 

<hdiv:config errorPage="/error.jsp">
    <hdiv:startPages>/</hdiv:startPages>
     <hdiv:paramsWithoutValidation>
          <hdiv:mapping url="/job/[0-9]*/.*/update.ht"  parameters=".*"/>
     </hdiv:paramsWithoutValidation>         
</hdiv:config>

All the files in the root folder(/) is considered as landing or starting page, so will be exampted from validation for hdiv state.

Important points:

1. Spring tags 3.0 and later has build in support for hdiv, so they can be simple used along with hdiv, but to use previous versions of spring tags, you may need to point your tlds to customized spring tlds, please refer the hdiv document for more details.

2. When using along with spring security or other frameworks which intercept the request and redirects to different pages, special care should be given otherwise it will end up in indefinite redirection loops. I had spring security in the project, so moved all the spring security related files(login, logout, etc) to different path which will not be intercepted by hdiv for more clarity. 

3. whenever accessing hdiv protected paths from non protected paths always use redirects as mentioned in the landing pages step above.


Some Points on hdiv-config.xml

There are three main sections in this file

1. <hdiv:config> section, which is  used to configure the start pages path, error page and validation exceptions 

2. <hdiv:validation> section, which is used to define the acceptable input formats 

3. <hdiv:editableValidations> section, which is used to associate the validations defined in <hdiv:validation> section with paths.

HDIV is really an added protection to the sites, developers may miss few things when protecting the site. By using a framework like HDIV, developers can concentrate more on building the logic than protecting each and every page. 

Give a try, post comment on how you go....






15 comments:

  1. Good one!! Can you give the configurations for using with Spring Security. I have tried with excluding the spring security pages in the hdiv-config.xml. But still, am not able to get to the login page. Is the landing or starting page should be applied to all the page?

    ReplyDelete
    Replies
    1. Thanks Magesh,

      Actually you have to exclude initial/landing hdiv hash generating page from spring security. In my example above the index.jsp file in Step 5 should be excluded in spring security. you don't need to exclude any thing else from hdiv or spring security. Hope it helps. All the best...

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Thanks for your response Nutpan. I ran into some other problems and is described below.

    I have included the initial landing page as index.jsp and redirected to the login page. The login page is displayed but the CSS and the images are not displayed.From the logger I could see the error message

    [ INFO] [http-bio-7780-exec-4 09:04:47] (Logger.java:log:66) HDIV_PARAMETER_NOT_EXISTS;/sample/login.htm;jsessionid=8960F3999D17C62D889620C4DB77D187;_HDIV_STATE_;null;127.0.0.1;127.0.0.1;user
    [ INFO] [http-bio-7780-exec-6 09:04:47] (MainController.java:displayLogin:61) Login Page GET MEthod called !
    [ INFO] [http-bio-7780-exec-7 09:04:50] (Logger.java:log:66) HDIV_PARAMETER_NOT_EXISTS;/sample/resources/img/header_bg.jpg;_HDIV_STATE_;null;127.0.0.1;127.0.0.1;user.


    Also after successful login, it is redirected to the error page defined in the hdiv-config.xml. From the log, I could see the following message.

    [ INFO] [http-bio-7780-exec-6 09:05:16] (Logger.java:log:66) HDIV_PARAMETER_NOT_EXISTS;/sample/home.htm;_HDIV_STATE_;null;127.0.0.1;127.0.0.1;user.

    Can you give any pointers on this regard ? What might be the problem ? I have included all the configurations as specified by you.

    ReplyDelete
    Replies
    1. I am able to get the image and the CSS. I have added the necessary configurations in excludedExtensions in hdiv-config.xml.

      Delete
    2. When I disable the HDIV Validator filter in the web.xml, the flow and all the webpages are displayed correctly. But if I enable the validator, always it is redirected to the error page.

      Delete
  4. Thanks. I was able to make it work!!!

    ReplyDelete
    Replies
    1. great Magesh... if you can share what was the problem you faced and how you overcome that, it will be useful for others.

      Delete
    2. Nuptan,
      I did not properly use the C tag. After inputting the correct syntax, I was able to do it correctly.


      Also, I have one question, can we exclude any page from the HDIV validation. Like, it is not the starting page, but it is some URL that caters to the AJAX request. I tried to configure it within the tag and it didnot work. Also what is the purpose of . DO you know anything about it?

      Delete
  5. Hi, I have configured HDIV as you have said. However, when I submit a form with text that would fail the editable validations it puts an error message in the log but it still proceeds as normal and submits the form to the controller; it doesn't block the request. Do you have any idea what could be wrong?

    Using spring 3.1.

    ReplyDelete
    Replies
    1. I'd like to add that it gives me the error page for all other applicable cases (missing parameters, wrong hdiv state,...)

      Delete
  6. using,
    hdiv-spring-mvc-2.5-2.0.3.jar
    hdiv-core-2.0.3.jar

    EditableParameterValidator is not working, I tried to debug the class, found
    Hashtable editableParameters = (Hashtable)RequestContextHolder.getRequestAttributes().getAttribute("org.hdiv.action.EDITABLE_PARAMETER_ERROR", 0);

    editableParameters - as null so its going as normal flow,

    ReplyDelete
  7. Hi,
    Is HDIV can be worked with Thymeleaf and html without jsp as front end.

    ReplyDelete
  8. Hi,

    I have an existing JSP based application which does not use servlets . The requests are submitted via JSP and processed by JSP using javabeans.

    Can HDIV be applied to this JSP based application. I see the HDIV docs say, they are only for frameworks like struts/spring.

    Since, this is a legacy application redesigning it is a difficult task. But, a lot of security issues have been identified in the application. so, to remediate them I am looking for a sensible option.

    ReplyDelete
  9. Thanks for the information. I am integrating HDIV with my struts1.3 application, I need your help as i am getting exception :

    SEVERE: Context initialization failed

    org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/hdiv-config.xml]; nested exception is org.springframework.beans.FatalBeanException: Invalid NamespaceHandler class [org.hdiv.config.xml.HdivNamespaceHandler] for namespace [http://www.hdiv.org/schema/hdi...]: problem with handler class file or dependent class; nested exception is java.lang.NoClassDefFoundError

    I am using following jars hdiv-struts-1-2.1.12.jar,spring-2.5.jar,hdiv-core-2.1.0.jar,hdiv-config-2.1.0.jar

    My hdic-config.xml looks like



    Please help me

    Thanks in advance

    Anand

    ReplyDelete