Posts

Setting Cookie Secure Flag – Java

Method #1

Create secure cookie by calling setSecure method, which allows cookie to be secure

Cookie newCookie = new Cookie("name","value");
newCookie.setSecure(true);

Method #2

Add the following lines to web.xml file of the project to make the cookie secure.

<session-config>
 <cookie-config>
 <secure>true</secure>
 </cookie-config>
</session-config>

Reference

https://www.owasp.org/index.php/SecureFlag

Setting the HttpOnly Flag – Java

For older versions of servlet

Add the following on cookie creation

String sessionid = request.getSession().getId();
response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; HttpOnly");

For servlet version 3.0 or later

Add the following lines into web.xml file

<session-config>
 <cookie-config>
  <http-only>true</http-only>
 </cookie-config>
<session-config>

Reference

https://www.owasp.org/index.php/HttpOnly#Using_Java_to_Set_HttpOnly

Clickjacking – Java Secure Coding

Method #1 Adding the X-Frame-Options in HTTP header

 // to prevent all framing of this content
 response.addHeader( "X-FRAME-OPTIONS", "DENY" );
 
 // to allow framing of this content only by this site
 response.addHeader( "X-FRAME-OPTIONS", "SAMEORIGIN" );

Method #2 Including frame busting code

<style> html{display : none ; } </style>
<script>
   if( self == top ) {
       document.documentElement.style.display = 'block' ; 
   } else {
       top.location = self.location ; 
   }
</script>

References

https://www.owasp.org/index.php/Clickjacking_Protection_for_Java_E

Prevention of Web Page Caching – JAVA

Method

Add the following codes into the page, in order to prevent the page being cached:

response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);

Reference

https://weblogs.java.net/blog/swchan2/archive/2013/08/29/when-httpsessio…

Setting Session Timeout – Java

Method#1

In servlet call getMaxInactiveInterval method with session object.

HttpSession session = request.getSession();
session.setMaxInactiveInterval(900);

(In this example, session time out is set for 900 seconds.)

Method#2

Set timeout through web.xml

<session-config>
  <session-timeout>10</session-timeout>
</session-config>

(Here 10 minute is the time out .)

Reference

http://docs.oracle.com/cd/E17802_01/webservices/webservices/docs/1.6/api…

SQLi – JAVA Secure Coding

Use PreparedStatement instead of dynamic queries.

All data access techniques provide some means for escaping SQL meta-characters automatically.
Variables passed as arguments to prepared statements will automatically be escaped by the JDBC driver.

String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();

References
https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java
https://www.java.net/node/678819
http://download.oracle.com/oll/tutorials/SQLInjection/index.htm

Anti CSRF Token – JAVA

Using OWASP ESAPI

  1. Download OWASP ESAPI Library from the ESAPI project page and add it to the library of the project.
  2. Generate a new CSRF token and add it to user login and store user in HTTP session.
  public String resetCSRFToken() {
    csrfToken = ESAPI.randomizer().getRandomString(8,DefaultEncoder.CHAR_ALPHANUMERICS);
    return csrfToken;
  }

3. Add the token as a parameter / hidden field, on any forms or URLs that should be protected.

   final static String CSRF_TOKEN_NAME = "cftoken";
   public String addCSRFToken(String href) {
	User user = ESAPI.authenticator().getCurrentUser();
	String token = CSRF_TOKEN_NAME + "=" + user.getCSRFToken();
	return href.indexOf( '?') != -1 ? href + "&" + token : href + "?" + token;
   }

   public String getCSRFToken() {
	User user = ESAPI.authenticator().getCurrentUser();
	if (user == null) return null;
	return user.getCSRFToken();
   }

4. On the server-side, check that the submitted token matches the token from the user object in the session.

   public void verifyCSRFToken(HttpServletRequest request) throws IntrusionException {
	User user = ESAPI.authenticator().getCurrentUser();
	if( request.getAttribute(user.getCSRFToken()) != null ) {
		return;
	}
	String token = request.getParameter(CSRF_TOKEN_NAME);
	if ( !user.getCSRFToken().equals( token ) ) {
		throw new IntrusionException("Authentication failed", "Possibly forged HTTP request without proper CSRF token detected");

	}

  }

References
https://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API
https://www.owasp.org/index.php/Category:OWASP_CSRFGuard_Project
http://code.google.com/p/owasp-esapi-java/downloads/list

XSS – Java Secure Coding

Using Security Encoding Library

  1. Download ESAPI.jar from the ESAPI Project page, and add it to library of the project.
  2. Import the package in jsp page: <%@ page language=”java” import=”org.owasp.esapi.*” %>
  3. Add code according to the different cases:

Case #1

HTML escape before inserting untrusted data into HTML element content.


<%
String safe = ESAPI.encoder().encodeForHTML( request.getParameter( "input" ) );
%>
<div><%= safe %></div>

Case #2

Attribute escape before inserting untrusted data into HTML common attributes.


<%
String safe = ESAPI.encoder().encodeForHTMLAttribute( request.getParameter( "input" ) );
%>
<div attr='<%= safe %>'></div>

Case #3

JavaScript escape before inserting untrusted data into JavaScript data values.


<%
String safe = ESAPI.encoder().encodeForJavaScript( request.getParameter( "input" ) );
%>
<script>alert('<%= safe %>')</script>
<input type=’button’ onclick=”alert('<%= safe %>')”>

Case #4
URL escape before inserting untrusted data into HTML URL parameter values.


<%
String safe = ESAPI.encoder().encodeForURL( request.getParameter( "input" ) );
%>
<a href='http://www.victim-site.com?test=<%= safe %>'>link</a >

References 
http://owasp-esapi-java.googlecode.com/svn/trunk_doc/latest/org/owasp/es…
http://code.google.com/p/owasp-esapi-java/downloads/list