How to prevent frame injection (clickjacking) in java application?

Hargovind Singh picture Hargovind Singh · Apr 24, 2015 · Viewed 15k times · Source

How can we prevent frame injection in Java application?

Like in a Penetration testing, it is found that if a hacker drafts a demo html page, and inside that page he has used iframe, which has the URL of the working application, he/she can see the data through that URL/request(created in an iframe).

suppose this is the hackers file, test.html:

<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"   \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head><body>
<iframe id="inner" src="http://hostname:8080/Application_Name/ABC/DEF/SomePage.jsp?ABC=QWERTYL&XYZ=1&CDE=24" width="600" height="400" scrolling="yes">

</iframe>
</body>
</html>

And now the hacker is able to retrieve the data within the application. How to stop this?

Answer

mies picture mies · Apr 24, 2015

This is clickjacking attack: https://www.owasp.org/index.php/Clickjacking The simpliest way to prevent it is to add header "X-Frame-Options" with value "DENY". This can be done using filter. Register it in your web.xml and use code like this:

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException,
            ServletException {
    HttpServletResponse response = (HttpServletResponse) resp;
    response.addHeader("X-Frame-Options", "DENY");    
    chain.doFilter(req, resp);
} 

All modern browsers support this header, but to protect users with legacy browsers you will need also defensive javascript in the UI. More details: https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet