Secure Java Coding Guidelines v3.0

When it comes to application security,  Secure coding is the first line of defense….and it is very critical to follow the best practice patterns and avoid pitfalls to secure the application from known risks and vulnerabities. The Java Security team has just released the updated – “Secure Coding Guidelines for the Java Programming Language, Version 3.0“ .  Certainly it included a newer set of fundamentals and enhanced set of secure coding guidelines.  

 A must have URL for your quick reference…if you are a security conscious developer !

Onlinerel Facebook Twitter Myspace Friendfeed Technorati del.icio.us Digg Google Yahoo Buzz StumbleUpon

Java EE 6: Web Application Security made simple !

Java EE 6 RI was released few weeks ago….I am bit late to have my first look :-)   Without a doubt, the new Web container security enhancements are very compelling for any budding or experienced Java developer working on Web applications. The Java EE 6 has unveiled several new security features with ease of use and targetted for simplified Web application security deployments. Based on Servlet 3.0 specification, the Java EE 6 Web applications can take advantage of an enriched set of programmatic and declarative security features and Security annotations previously available to EJB 3.x applications. Also, the deployed Web applications/Web Services can use JSR-196 based pluggable authentication/authorization modules (based on SOAP Web Services) that can be configured as part of the Servlet container.

 

 Java EE 6 : Programmatic Security for Web Applications

The newly introduced Java EE 6 programmatic security features for Web applications are represented by the following methods of HttpServletRequest interface:

 

1. authenticate()

  • This method helps to initiate authentication of the calling user by launching an authentication dialog for acquiring username/password and perform BASIC authentication by the container within an unconstrained request context.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

 

public class MyAuthServlet extends HttpServlet {

 

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

                     throws ServletException, IOException {

            response.setContentType(“text/html;charset=UTF-8″);
            PrintWriter out = response.getWriter();

   try {

     //Launch the BASIC authentication dialog
                request.authenticate(response);
                     out.println(“Authenticate Successful”);

            } finally {

                          out.close();

         }

 

          public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                   processRequest(request, response);

        }

 

           public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                processRequest(request, response);

          }

}

 

 

2. login() and logout ()

  • The login() method allows to programmatically collect with the provided username/password credentials (as an alternative to FORM-based authentication) and perform user authentication.
  • The logout() method performs logging out the user and resets the context.

 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

 

public class MySecurityServlet extends HttpServlet {

 

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

                                                   throws ServletException, IOException {

   response.setContentType(“text/html;charset=UTF-8″);
   PrintWriter out = response.getWriter();

   try {

              String myUsername = request.getParameter(“UserName”);
             String myPassword = request.getParameter(“Password”);

           try {

                 request.login(myUsername, myPassword);

                   } catch(ServletException ex) {

                            out.println(“Login Failed” + ex.getMessage());

              return;

     }

    }   catch (Exception e) {

                 throw new ServletException(e);

            } finally {

                request.logout();
              out.close();

             }

     }

      public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

             processRequest(request, response);

        }

      public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

              processRequest(request, response);

      }

}

 

The above code assumes the authentication is configured to BASIC by setting the login-config element in web.xml. If the authentication is the successful, the Web application can take advantage of the following methods in the HttpServletRequest interface to identify the remote user, role attributes and to perform business logic decisions.

 

3. getRemoteUser()

  • Determines the authenticate username of the remote user associated with the request. If no authentication occured, it will return a null value.

4. IsUserInRole(..rolename..)

  • Determines whether the authenticated user is in a specified security role. If the user is not authenticated, it returns false.

5. getUserPrincipal()

  • Determines the principal name that represents the authenticated user entity (name of the remote user) and returns a java.security.Principal object corresponding to the user.

Here is my sample code that I tested it on Glassfish v3 (Developer Sample):

 

 

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import javax.annotation.security.DeclareRoles;

 

  //Annotation for defining the Servlet name and its URL pattern
  @WebServlet(name=”MySecurityServlet”, urlPatterns={“/MySecurityServlet”})

 

  // Annotation for declaring roles
   @DeclareRoles(“securityguy”)

public class MySecurityServlet extends HttpServlet {

 

              protected void processRequest(HttpServletRequest request, HttpServletResponse response) 

                                   throws ServletException, IOException {

 

                                     response.setContentType(“text/html;charset=UTF-8″);
                                     PrintWriter out = response.getWriter();

               try {

                                    String myUsername = request.getParameter(“UserName”);
                                    String myPassword = request.getParameter(“Password”);

              try {

                                   request.login(myUsername, myPassword);

                                  }      catch(ServletException ex) {

                                   out.println(“Login Failed” + ex.getMessage());

                                   return;

                   }

                                              out.println(“The authenticated user is in Role: ” + request.isUserInRole(“securityguy”));
                                              out.println(“The authenticated remote username: ” + request.getRemoteUser());
                                             out.println(“The authenticated Principal name: ” + request.getUserPrincipal());
                                             out.println(“The authentication type: ” + request.getAuthType());

                   } catch (Exception e) {

                                  throw new ServletException(e);

                }  finally {

                                request.logout();

                                out.close();

             }

   }

       public void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {

                    processRequest(request, response);

        }

        public void doPost(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {

                   processRequest(request, response);

      }

}
 

To test the code, it is assumed that you have the Java EE runtime deployment descriptor include the appropriate role mapping that associated the user with the specified role-name.

 

Security Annotations for the Web Applications

With Servlet 3.0 implementation, we would able to use standard Java annotations for declaring security constraints as equivalent to those defined in a standard Web deployment descriptor (web.xml). With Security annotation you should able to define roles, access control to HTTP methods, transport-layer protection (for enforcing SSL/TLS). To make use of security annotations in Servlets, Servlet 3.0 has introduced @ServletSecurity annotation to support defining security constraints.

 

Using @ServletSecurity

 

The @ServletSecurity annotation allows to define the security constraints as its fields:

  1. @HttpConstraint  – Used as a field of @ServletSecurity to specify roles to all methods and ensure transport-layer security)
    • ex.  @ServletSecurity(@HttpConstraint(rolesAllowed={“customer”})) - Ensures all HTTP methods (GET, POST, TRACE) are protected and access is allowed to security role “customer”.
    • ex. @ServletSecurity(@HttpConstraint(transportGuarantee=ServletSecurity.TransportGuarantee.CONFIDENTIAL)) – Ensures all methods require SSL transport
  2. @HttpMethodConstraint (Applied to define methods ex. GET, POST, TRACE)
    • ex. ServletSecurity(value=@HttpConstraint(httpMethodConstraints={ @HttpMethodConstraint(value=”POST”, transportGuarantee=ServletSecurity.TransportGuarantee.NONE, rolesAllowed={“customer”}) })  – Ensures only authenticated users with security role is allowed to access HTTP POST method and transport-layer security/SSL is supported but not required.
  3. @DeclareRoles (Allows to define security roles)
  4. @RoleAllowed (Allows to define authorized roles)

Here is a quick usage scenario of @ServletSecurity annotation (Developer Sample):

 import java.io.*;
 import javax.servlet.*;
 import javax.servlet.http.*;
 import javax.annotation.security.*;
 @DeclareRoles("customer","guest")
 @ServletSecurity(@HttpConstraint(rolesAllowed={"customer"}))
 public class MyHelloWorld extends HttpServlet {
     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("Hello World");
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
     out.println("Hello World");
     out.close();
  }
}  
 

Sometimes, it’s the small things that make even complex things much easier. Way to go…Java EE 6 ! 

 

Here is couple of references, you may consider to explore Java EE 6:

Java EE 6: New Enhancements

Glassfish v3/Java EE 6 Sample Applications

 

Enjoy :-)

Onlinerel Facebook Twitter Myspace Friendfeed Technorati del.icio.us Digg Google Yahoo Buzz StumbleUpon

Drone video feeds got eavesdropped ?

Interesting news..I am not sure how far this story is true !  The Iraqi insurgents has used the SkyGrabber utility to eavesdrop the live video feeds from the US Drones…as reported by Wallstreet journal yesterday.  Quite interesting to note, the multi-million dollar unmanned aircraft did’nt use “Encrypted Communication” in first place.

It’s time for them to deploy a tamper-proof encrypted communication for ensuring high-degree of confidentiality and integrity…without compromising the performance, so a wire-speed cryptography solution might help..as posted in my previous entry

:-)

Onlinerel Facebook Twitter Myspace Friendfeed Technorati del.icio.us Digg Google Yahoo Buzz StumbleUpon

The untold reality is ….when your Web application on the DMZ hits the Internet… the colorful performance graphs/numbers does’nt mean anything !  Unless your performance guru in the lab captured the QoS requirements and realized it proactively and accounted its actual overheads associated with Security, Network bandwidth, High-availability and other mission-critical requirements.  Otherwise…performance is the nagging issue that every datacenter guy gnaws…. when an application bloats up with its cryptograhic shields such as SSL  and WS-Security and then goes into production.   If you are one of them in the datacenter, who is pulling the hair out on Security performance issues and compelled to meet the SLA including IT Security and compliance requirements mandating the use of cryptography for securing the exposed application layers  – transport, data and network – Then this Sun solution blueprint should help you for accelerating the real-world performance of Java EE based Web applications (especially Oracle Weblogic) delivering Security ground-up and all WITHOUT  your performance engineer help   :-)

No magic or surprises – The Sun CMT server features On-chip Cryptography and multi-threaded 10GbE networking out of the box – No kidding! If you are curious to know more or seize the power of your Sun CMT servers for security, take a look at the blueprint and also take a look at my previous post highlighting our presentation at Oracle Open World -  Wire-speed Cryptographic Acceleration for SOA and Java EE Security.

Onlinerel Facebook Twitter Myspace Friendfeed Technorati del.icio.us Digg Google Yahoo Buzz StumbleUpon

Cloud Security…. Cannot be overstated than Dilbert !

Absolutely…Security cannot be an afterthought when it comes to hosting on Cloud.

Onlinerel Facebook Twitter Myspace Friendfeed Technorati del.icio.us Digg Google Yahoo Buzz StumbleUpon

Dilbert on Cloud Computing :-)

That’s is the true reality of real-world adoption of Cloud….

Onlinerel Facebook Twitter Myspace Friendfeed Technorati del.icio.us Digg Google Yahoo Buzz StumbleUpon

CyberSecurity hits Primetime!

Last night, CBS ran a 60 Minutes report on “Sabotaging the System” highlighting the potential dangers associated with the security vulnerabilities of critical government IT systems. More than news, CBS presented this story with special insights from cybersecurity experts and disclosed some scary facts…serious stuff and hard to ignore ! I am sure this story will raise the heat on some who don’t understand or proactive to IT security….. if you missed the story, it is right here:

 

Sabotaging the System

Sabotaging the System

 

Overall, the CBS story is a “wakeup” call for those still consider IT security as an afterthought -  hope we don’t see another epidemic chaos in IT !  
:-(

Onlinerel Facebook Twitter Myspace Friendfeed Technorati del.icio.us Digg Google Yahoo Buzz StumbleUpon

Important Disclaimer:The information presented in this weblog is provided “AS IS” with no warranties, and confers no rights. It solely represents our opinions. This weblog does not represent the thoughts, intentions, plans or strategies of our employers.
.