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 🙂

Drone video feeds got eavesdropped ?

      No Comments on 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

🙂

Does your Performance Tests address Security ?

      2 Comments on Does your Performance Tests address Security ?

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.

CyberSecurity hits Primetime!

      No Comments on 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 !  

🙁

Design Patterns: 15 years now and counting…

      No Comments on Design Patterns: 15 years now and counting…

Time flies..it is amazing to know, yesterday marked the 15th anniversary of Design Patterns: Elements of Reusable Object-Oriented Software by Gang of Four (Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides),  a seminal work in object-oriented software design and development that changed the way how we think and solve software implementation problems. In simpler terms., Design patterns is all about adopting to proven solutions evolved from prior experiences and the known bestpractices/pitfalls without ending up reinvent the wheel ! In my experience, using design patterns helped understanding the architecture and design the software right at the first attempt and resulting reusable code artifacts – easier to reuse with subsequent design and development process.

When Chris and I started our security patterns work… unthinkably..the GoF patterns and its core principles has always been our primary source of guidance for evolving the Security Patterns catalog.  With 14+ years passed by, the Design patterns book has never gone out off my sight and always remained in my reaching distance… when so many other books collecting dust in my shelf !  Now, my shameless promotion… about celebrating the 15th anniversary of Design Patterns – Prentice Hall/Addison Wesley is bringing out a series of interviews (featuring GoF and others), articles and takes this opportuntity to further influencing the relevance of Design patterns books with 30% off on the cover price.. Here you go:

Enjoy…

Wire-speed Cryptography for SOA Security and Compliance

I admit that I am not a SOA expert or pretend to be one !  Lately, I had a chance to explore few security features intended for securing XML Web Services and Java EE applications. With my little knowledge to SOA, I found that XML Web services play a vital role in SOA to enable loosely-coupled services and ensuring interoperability. From a security perspective, the core foundation of securing SOA solutions  builds on XML Web Services Security standards and the underlying Java platform (unless you are using Microsoft .NET) . Last two weeks, Chad Prucha and I were test-driving SOA applications using Oracle Weblogic and Oracle Fusion Middleware on a Sun CMT server (T5440) particularly test driving SSL and WS-Security scenarios using WS-Policy/WS-SecurityPolicy standards.  Our primary aim was to take advantage of On-chip Cryptographic acceleration provided by the UltraSPARC T2 processors of the T5440 server supporting the cryptographic mechanisms/cipher suites used by SSL and WS-SecurityPolicy. Believe it or not, it worked as piece of cake…. and the performance numbers were stunningly amazing. The Sun CMT servers (using its on-chip crypto accelerators) cruised on SSL and WS-Security with its cryptographic performance….RSA, AES, SHA2…too long to list here.  If you consider yourself as a SOA enthusiast and have these following questions – Why should we care about Wire-speed Cryptographic acceleration for SOA or J2EE or XML Web Services performance ?  Why it should even be considered in first place ? Is there is any security benefits ?  If you do have those questions, then you may find this blog entry helpful otherwise please ignore.

Wire-speed Crypto Acceleration for SOA Security

Cryptographic operations plays a critical role in securing SOA application components particularly Java EE (formerly J2EE) applications and XML Web services supporting their transport-layer security (SSL) and message-layer security (WS-Security including XML Encryption, XML Digital Signature, WS-Policy, WS-SecurityPolicy) requirements. Adopting to cryptographic techniques helps IT organizations securing critical application infrastructures and adhere to industry-specific regulatory compliance mandates such as PCI DSS, HIPAA, FISMA and so forth.

But using Crypto for accomplishing SOA Message-level and Transport-level security induces significant performance degradation and taxes your CPU, Memory and Network bandwidth.  SOA security experts often resort to using dedicated XML security appliances for delegating CPU intensive cryptographic operations such as Public-key cryptography (ex.RSA, DSA) based encryption and digital-signature, Symmetric-key based encryption (ex. AES, 3DES) to dedicated hardware-based accelarators – Which helps freeing up the main CPU resources and resulting significant performance gains in overall application throughput.  In simpler terms, cryptographic accelerators and HSMs allows offloading computationally expensive  cryptographic functions to dedicated hardware that supports cryptographic algorithms and handle cryptographic operations. Under the hood, the cryptographic functions are usually pushed through PKCS#11 standard interfaces using Solaris Cryptographic Framework (On Solaris) and OpenCryptoki (On Linux), or CryptoAPI framework (CAPI/CNG) in the case of Microsoft Windows environment.  As a result, cryptographic accelerators proven to demonstrate significant gains in SOA application throughput and scalability by reducing the known CPU bottlenecks and related latency issues caused by cryptographic operations.

Over the past year I have become a big fan of Sun CMT Servers — and more specifically its Cryptographic capabilities, which makes it very compelling for delivering ultra-fast security for security sensitive SOA and Java EE applications.

On-chip Crypto Acceleration using Sun CMT Servers

Sun CMT servers are (Based On UltraSPARC T1/T2/T2Plus processors) based on Chip Multithreading Technology – CMT, which introduced on-chip cryptographic acceleration support through a dedicated cryptographic accelerator implemented on each core of the chip (8 Crypto Accelerators/Chip) – referred to as “Niagara Crypto Provider” (NCP). The introductory UltraSPARC T1 processor included a NCP implementation that facilitated public-key cryptographic mechanisms including RSA and DSA algorithms. The latest UltraSPARC T2 and T2+ processors extended more algorithms support by introducing symmetric-key based encryption/decryption mechanisms such as DES, 3DES, AES-128, AES-192, AES-256, RC4, Hashing operations such as MD5, SHA1, SHA256 and support for ECC algorithms (ECCp-160 and ECCb-163). In addition, the UltraSPARC T2 processors provides an on-chip Random Number Generator (N2RNG) to support random number generation operations intended for cryptographic applications. In practice, NCP makes use of Solaris Cryptographic Framework (SCF) for allowing user-level applications to offload their cryptographic operations and in effect the user applications can take advantage of NCP based on-chip cryptographic acceleration.

You had the gist of the story…now I am rushing out to catch the plane to Boston in an hour…… ! Yes, last three days I was attending  Oracle Open World and co-presented with Chad on topic  “Wire Speed Cryptography for SOA and Java EE applications” – In our presentation, we put together all the concepts and  tried our best to illustrate the applied crypto mechanisms related to SOA security and the secret sauce configuration/deployment of Sun CMT based cryptographic acceleration for delivering wire-speed security performance for SOA and Java EE applications.  You may find the presentation is tailored to Oracle SOA and Weblogic but frankly speaking it applies well to all Java EE based SOA application deployments.

Click here to download the slides

Enjoy the slides for now ! Feel free to ping for questions………all I can promise now… is sooner you will see a detailed Sun Blueprint on this topic ! So please stay tuned.

🙂

Unleashing SSL Acceleration and Reverse-Proxying with Kernel SSL (KSSL)

Last few weeks, I have been pulled into an interesting gig for demonstrating security for _____  SOA/XML Web Services and Java EE applications…. so I had a chance to play with some untold security features of Solaris 10. KSSL is one of the unsung yet powerful security features of Solaris 10.  As the name identifies, KSSL is a Solaris Kernel Module that helps representing server-side SSL protocol to help offloading operations such as SSL/TLS based communication, SSL/TLS termination and reverse-proxying for enduser applications. KSSL takes advantage of Solaris Cryptographic Framework (SCF), to act as an SSL proxy server performing complete SSL handshake processing in the Solaris Kernel and also using the underlying hardware cryptographic providers (SSL accelerators, PKCS11 Keystores and HSMs) to enable SSL acceleration and supporting secure key storage.

Before I jump into how to use KSSL for offloading SSL operations, here is some compelling aspects you may want to know:

  1. Helps non-intrusively introduce an SSL proxy server for Web servers, Java EE application servers and also applications that does’nt implement SSL.
  2. KSSL proxy listens to all secured requests on the designated SSL port (ex. HTTPS://:443)  and renders a cleartext traffic via reverse proxy (ex. HTTP://:8080) port for the underlying Web or application server. All SSL operations including the SSL handshake and session state are performed asynchronously in the Solaris Kernel and without the knowledge of the target application server.
  3. KSSL automatically uses SCF for offloading operations to underlying hardware cryptographic providers with no extra effort needed.
  4. Manages all the SSL certificates independently supporting most standard formats (ex. PKCS12, PEM),  the key artifacts can be stored in a flatfile or a PKCS11 conformant keystore (If you are worried about loosing the private key).
  5. Supports the use Solaris zones, where each IP identified zone can be configured with a KSSL proxy
  6. Delivers 25% – 35% faster SSL performance in comparison with traditional SSL configurations of most popular Web servers and Java EE application servers.
  7. KSSL can be used to delegate Transport-layer security and the applications may choose to implement WS-Security mechanisms for message-layer security.

Those are some compelling aspects of KSSL that are hard to ignore…. if you really understand the pain from performance overheads associated with SSL/TLS 🙂  As I verified, KSSL works well with most common Web servers and Java EE applications servers.

Try it yourself

Certainly it is worth a try…and you should able to do it very quickly than configuring SSL for your web sever !

  • Obtain your server SSL and CA certificates. If you just want to test-drive KSSL and considering to using a self-signed OpenSSL certificate.. just follow the example commands and make sure that your web server hostname is correct. If you choose to use a flatfile based SSL keystore, KSSL requires to have all your certificate artifacts (including private key and certificates) in a single file.  If you need more OpenSSL help, read my earlier post.

          Ex. To create a self-signed server certificate using OpenSSL (in PEM format).

    openssl req -x509 -nodes  -days 365 -subj
     "/C=US/ST=Massachusetts/L=Burlington/CN=myhostname"
    -newkey rsa:1024  -keyout myServerSSLkey.pem -out mySelfSSLcert.pem

           Ex.  Concatenate the server certificates in a single file.

    cat mySelfSSLcert.pem myServerSSLkey.pem > mySSLCert.pem
  • Configure the KSSL proxy service,  assuming the secured requests are forwarded to an SSL port (ex. 443) and the reverse-proxy of your backend Web server listens to a non-SSL port (ex. 8080). Use -f option to identify the certificate fomat, to represent PEM (-f pem) and to represent PKCS12 (-f pk12).  If the certificates are located in a HSM/PKCS11 Keystore, use -f pkcs11 to identify the token directory, -T to identify the token label and -C to identify the certificate_subject.

          Ex. To configure the KSSL proxy service with SSL Port 443 and reverse-proxy port is 8080 using PEM based certificates and the passphrase stored in file (ex. password_file).

           ksslcfg create -f pem -i mySSLCert.pem -x 8080 -p password_file webserver_hostname 443
  • Verify the KSSL proxy service under Solaris Service Management Framework (SMF) controls, the KSSL services is identified with FMRI svcs:/network/ssl/proxy.
                    svcs - a | grep "kssl"
  •  Assuming your webserver in the backend listens at port 8080, you should able to test the SSL configuration provided by the KSSL proxy.  Open your browser, goto https://webserver_host:443/ you should be prompted by the SSL dialog warning to accept a self-signed certificate.
  • More importantly, if your Solaris host is a Sun CMT server (based on UltraSPARC T1/T2 processor), KSSL automatically takes advantage of the cryptographic acceleration and no additional configuration is necessary.

Here is an unofficial benchmark that highlights performance comparisons with KSSL and other SSL options.  The following shows the latency of an Web application running on Oracle Weblogic server using different SSL configurations (Certificate using RSA 1024) on a Sun CMT server (T5440) – To interpret the graph, make a note “Smaller the Latency means Faster”.

 

Adopting to Sun CMT servers (based on UltraSPARC T1/T2 processors) helps delivering on-chip cryptographic acceleration for supporting SSL/TLS and its cryptographic functions. With KSSL based SSL deployment, you will atleast get an additional 30% performance advantage while comparing with other Web server based SSL deployments. I heard that Intel Nehalem EX processors are expected to provide similar on-chip crypto capabilities, not sure !  Either way, using KSSL is a no brainer and it works.  If you are itching the head to provide transport-layer security for your applications, this could be easiest way to go !  Ofcourse, it can help you score some points in those IT infrastructure security assessment checklists verifying for PCI-DSS, FISMA, HIPPA and/or similar regulatory/industry compliance mandates !  🙂

Exploring Logical Access Control with PIV cards

      No Comments on Exploring Logical Access Control with PIV cards

Looks like convergence projects are in the limelight… lately I noticed a lot of interests on enabling the use of common credentials for securely accessing physical and logical resources.  Although we find most convergence projects are targeted at the enterprise level but there are serious minds working on using smartcard based PKI credentials for supporting citizen-scale projects (I regret that I cannot discuss the specifics) !  Ofcourse the use of on-card PKI credentials and its on-demand verification with the PKI service provider is in practice for a while now at security sensitive organizations. The DoD CAC, PIV and most smartcard based National ID/eIDs contain PKI certificate credentials and few of them includes Biometric samples of the card holder as well. Using those on-card identity credentials for accessing physical and logical resources becomes critical and also makes sense to  fulfil the ultimate purpose of issuing smartcard based credentials… it cannot be overstated.

Couple of weeks ago, I had a chance to present and demonstrate PIV card credentials based logical access control using Sun IDM, OpenSSO Enterprise, WinXP running on Sun Ray environment. The demo was hosted  one of the Big5 SI.  If you curious to see my preso detailing the pieces of the puzzle…here you go: