Monday Jan 31, 2011

Secure Communication between Web-app and EJB3.x in GlassFish

This post describes how one could make secure calls to an EJB (3.x) from a web application using SSL or MUTUAL_SSL, even when the web-app and the EJB are running on GlassFish instances in different host machines.

Wth the following <ior-security-config> in the EJB (glassfish-ejb-jar.xml), SSL is forced by the EJB.




With the following annotation in the servlet:

   private SecureEjbRemote secureRemote;

and the following element in glassfish-web.xml, the client (servlet) is forced to contact the Ejb securely (using the MUTUAL_SSL ORB port 3820)

 <jndi-name>corbaname:iiop:<host in which EJB is deployed>:3820#SecureEjbBean</jndi-name>

With the following jvm-option added to the domain.xml of the host in which the web-app is deployed,


secure communication happens between the servlet and the EJB for the name service lookup (before the EJB create call)

Thursday Jan 27, 2011

Change in the default digest algorithm in FileRealms (GF 3.1)

In GlassFish 3,1, the digest algorithm for storing file users in the keyfiles for the FileRealm based realms has been changed to SHA-256 from the previous SHA-1. This includes the default realm - file and the admin-realm. The change can be observed in respective keyfiles - keyfile and admin-keyfile - The SSHA256 tag and a longer digest  than the earlier SSHA tag (representing SHA-1 algorithm).

 Keyfile and admin-keyfile in GlassFish 3.1



Keyfile and admin-keyfile prior to GlassFish 3.1



 Support is provided for users created in versions of GlassFish prior to GlassFish 3.1 and upgraded to the latest 3.1. The decoding mechanism interprets the algorithm to be used for decoding the digest. However while creating new users in the latest version (3.1), only SHA-256 is employed. This change has been effected since SHA-256 is known to provide better security than SHA-1. To the end-user, there is no difference in the usage of file user passwords.

Tuesday Jan 25, 2011

PAMRealm in GlassFish 3.1

A new realm (PamRealm) has been made available in GlassFish 3.1 for  Unix based OSx (Solaris, Linux, MacOS). PAMRealm is based on the Pluggable Authentication Module (PAM) mechanism of the underlying Unix OSx. If this realm is configured for an application deployed in GlassFish, users created in the underlying OSx can authenticate themselves to access an application, with their Unix passwords.

PamRealm can be configured either through the admin-console (server-config->Security->Realms->New). This realm can be chosen from the dropdown in the list of Realm classes. The jaas-context for the realm is pamRealm.

 This realm can also be configured using the asadmin CLI :

./asadmin create-auth-realm --classname --property jaas-context=pamRealm PamRealm
Command create-auth-realm executed successfully.

The pamRealm jaas-context has been mapped to the following LoginModule class in login.conf

pamRealm { required;

To configure this realm, GlassFish should be installed as the root user (that can access the PAM's underlying authentication files in Unix)

Wednesday Nov 24, 2010

Change in the default digest-algorithm of JDBCRealm in Glassfish v3.1

In GlassFish 3.1, a change has been made to make the default-digest algorithm to be used in JDBCRealm configurable in domain.xml, the default configured value being SHA256. Earlier the default-digest-algorithm was MD5. So, for existing applications (which use digest-algorithm MD5) to work seamlessly in the latest builds, the default-digest-algorithm can be changed to MD5 by changing this property in the security-service element of domain.xml:

<property name="default-digest-algorithm" value="SHA-256"></property> 

Another option is to update the specific JDBCRealm to include the digest-algorithm property (MD5). This would override the default-digest-algorithm in the security-service element and set the it to the value specified in the auth-realm element. 

<auth-realm name="test" classname="">

<property name="digest-algorithm" value="MD5"></property>



If an upgrade is performed from v2 or v3 to v3.1, this change of default algorithm is handled (i.e) for JDBCRealms in Glassfish v2x or v3, that did not specify any digest algorithm , on migration to v3.1, the digest-algorithm is specified as MD5(the old default) in the upgraded version so that the realms in the old versions are compatible in GlassFishv3.1. 

Friday Sep 17, 2010

A Simple Secure Embedded Web Test Client in GlassFish v3.1

Following the posts (i), (ii) , (iii) related to deploying secure ejb applications in the Glassfish embedded mode, this post is about deploying a secure web-application in GlassFish in the embedded mode. Similar to the EmbeddedEjbContainer API, the EmbeddedWebContainer API in glassfish v3.1 can be used to deploy webapps. The deployed web-app could either be accessed using a URLConnection in the same EmbeddedTest Client or from a browser (provided the Embedded server with the Container is still running).In this post, we look at deploying a secure webapp (web-app protected by a user-data constraint)

Consider a simple webapp that is protected by a user-data constraint.


To test this war file, one could write a simple Embedded Web Test Client that uses the EmbeddedWebContainer API to deploy this app.As can be observed from this test client, the server containing the embeddable webcontainer is not stopped immediately on program exit. So the deployed web-app can be accessed from a browser (http://localhost:8080/simpleweb). Since this app is protected by a user-data constraint, the redirection to https and the secure port (8181) can be observed.

Monday Mar 29, 2010

Accessing ORB service securely in GlassFish v3

Transport Security in EJB is indicated by the IOR  (Interoperable Object Reference ) security representation of the ORB (Object Request Broker) layer. In Glassfish, the security-configuration information for the ORB is specified using the <ior-security-config> element of the sun-ejb-jar.xml.  The <transport-config> is a child element of the <ior-security-config> and is the root element for security between the end points.

<!ELEMENT transport-config ( integrity, confidentiality, establish-trust-in-target, establish-trust-in-client )>

The integrity and confidentiality child elements indicate if the target requires/supports integrity-protected or privacy-protected messages. The valid values are NONE, SUPPORTED or REQUIRED.

<!ELEMENT integrity ( #PCDATA)>
<!ELEMENT confidentiality ( #PCDATA)>

The establish-trust-in-target and establish-trust-in-client elements indicate if the target (server) is capable of authenticating to a client.

The transport between the client and the server can be secured with an <ior-security-config> element that is similar to :



However with the above IOR configuration, the client is not guaranteed to contact the name service securely (the service that is invoked by a call to InitialContext.lookup() ). This service usually runs on port 3700 non-securely and on port 3820 securely in Glassfish. By default, the client contacts the name service of the application server non-securely on port 3700 . To secure this connection in GlassFish v3, the following techniques could be used:

1. When using an application client, the sun-acc.xml in <domain-dir>/config should be modified to include a security element inside the target-server parent element:

<target-server name="localhost" address="localhost" port="3820">


This indicates to the server that the client demands a secure ORB connection. While running the appclient, the following system properties are passed:<domain-dir>/config/cacerts.jks<domain-dir>/config/keystore.jks<password><password>

-Dorg.omg.CORBA.ORBInitialPort=3820 (This forces the client to contact the secure ORB service provided by the application server.

Now, on running the appclient with the above system properties, the name service connection is also secured along with the other transport.

2. When using a standalone POJO client, in addition to setting the above system properties , an additional property for indicating the client's preference for secure ORB connection is to be set:


With this, the client can contact the name service of the server securely. This feature is available in the latest trunk builds of GlassFish v3.

Wednesday Mar 17, 2010

Running a secure application in Glassfish Embedded Server - Part II

Following the previous post illustrating how to run a secure ejb application on GlassFish embedded server, this post aims to focus on running a secure web application using GlassFish embedded server. Here is a sample web-app (with context-root - simpleweb) and restricts access to file users of group "tester". (Please examine the web.xml and sun-web.xml for details). It has been configured for BASIC auth using file-realm. To test this web-app, an embedded server could be configured to use an existing non-embedded GlassFish instance's filesystem. The web-app could then be deployed on this embedded server.

        Server.Builder builder = new Server.Builder("web-test");
        EmbeddedFileSystem.Builder efsBuilder = new EmbeddedFileSystem.Builder();
        efsBuilder.instanceRoot(new File(instanceRoot));
        Server server =;

        EmbeddedDeployer deployer = server.getDeployer();
        String appName = deployer.deploy(new File(testWarDir, testWar), null);
        System.out.println("Deployed " + appName);

The non-embedded GlassFish instance should be configured to contain file users of group tester (that has been configured in sun-web.xml of the web-app).

./asadmin create-file-user --groups tester testuser

Now, the web-app can be accessed from the browser. (http://localhost:8080/simpleweb). In response to the challenge, the username (testuser) and password are provided to access the protected page. Here is the complete test file.

PS - The Embedded API in GlassFish 3.1 has undergone some changes (from the API used in this blog post. Please refer to this link for the latest Embedded API)

Thursday Feb 18, 2010

Running a secure application in Glassfish Embedded Server

The embedded server and the embedded API are a key new feature offered by the Glassfish v3 server. Among many advantages, it offers the ability to deploy and test web/ejb applications using an embedded server that can be run on the same VM as the test application. This document provides details on the embedded server, deploying and running applications and discusses the embedded API. If a user wants to deploy a secure application with protected methods, the user has to provide authentication credentials to the embedded server before invoking the protected methods. This post discusses how this could be done.

Lets consider a secure EJB, whose methods are protected by the RolesAllowed annotation - allowing access to users with role 'admin'. Let's assume that this role is mapped to the group admin using the sun-ejb-jar.xml. If not, the default principal-role-mapping could be enabled in the embedded server. To run the application, the ProgrammaticLogin API could be used to provide auth credentials. There are two ways to do access the file realm users: (i) Use an existing non-embedded instance of glassfish with existing file users and set it as the embedded server's file system. (ii) Use the asadmin command to create file users in the default embedded server.

Approach I - Using an existing instance of glassfish:

1. Create a file user (embedtester) belonging to the specified group (admin) in an existing non-embedded glassfish server instance using the admin console or the CLI.

2. If required, turn on the default principal-role mapping for the instance (through the admin-console or CLI) - when no principal-role mapping is provided in the application's sun-ejb-jar.xml

3. Using the following code snippet, use the instance to be set as the embedded server's instance root:

        EmbeddedFileSystem.Builder efsBuilder = new EmbeddedFileSystem.Builder();       
        efsBuilder.instanceRoot(new File(
<path to glassfish instance domain directory>));
        efsBuilder.configurationFile(new File(
<path to glassfish instance domain.xml>));
        Server.Builder builder = new Server.Builder("test");
        Server server =;

4. After deploying the embedded ejb (refer the document for more details ) , before invoking the protected method on the Ejb, call the ProgrammaticLogin's login method to authenticate the user:

            ProgrammaticLogin pgLogin = new ProgrammaticLogin();
            pgLogin.login("embedtester", "abc12345", "file", true);

Approach II - Creating file users using the asadmin command in the embedded server:

If the default embedded server has to be used without setting an existing configuration or instanceRoot, file users could be created in the embedded server using the asadmin command.

1. Create the embedded server and start it.

2. Run the asadmin create-file-user command :

        String command = "create-file-user";
        ParameterMap params = new ParameterMap();
        params.add("userpassword", "abc12345" );
        params.add("groups", "admin");
        params.add("username", "embedtester");
        CommandRunner runner = server.getHabitat().getComponent(CommandRunner.class);
        ActionReport report = server.getHabitat().getComponent(ActionReport.class);
        runner.getCommandInvocation(command, report).parameters(params).execute();

2. Deploy the application and invoke ProgrammaticLogin.login() before calling the protected method.

            ProgrammaticLogin pgLogin = new ProgrammaticLogin();
            pgLogin.login("embedtester", "abc12345", "file", true);

The ProgrammaticLogin API ( is available as a part of security.jar in <GF-DOMAIN-DIR>/modules directory. Here is a sample test client (and the ejb) that invokes a protected method of the ejb (HelloWorldBean).

PS - The Embedded API in GlassFish 3.1 has undergone some changes (from the API used in this blog post. Please refer to this link for the latest Embedded API)

Friday Feb 05, 2010

New Security Features in Glassfish v3 (Java EE 6) - Part III

The login() method 

In continuation of the previous articles discussing the new security features in Servlet 3.0 in GlassFish v3, this post aims to discuss about the other programmatic way to login to a web application - the login method of the HttpServletRequest API. -

  HttpServletRequest.login(String username, String password) throws ServletException

Similar to the authenticate() method, the login() method serves to authenticate a given username and password programatically. As mentioned in this blog post, this method throws a ServletException when the validation of username, password provided fails or if the caller identity has been already established before a call to this method or if the configured login mechanism (in web.xml) is does not support username, password validation.

A recent fix was made to have the authentication state in the existing session after a successful login. The session is created if it does not exist at this time to store the auth state. In the orthogonal HttpServletRequest.logout() method, this authentication state is cleared from the session. This change is available in the GlassFish v3 trunk and in the upcoming releases of GlassFish.

Thursday Dec 24, 2009

New Security Features in Glassfish v3 (Java EE 6) - Part II

The authenticate() method

In continuation of the post on the new security features in Java EE 6  that focused on http-method-omissions, this post aims to elucidate yet another feature in servlet security introduced in Java EE 6 (and implemented in Glassfish v3) - the authenticate() method.

This method is provided in the javax.servlet.http.HttpServletRequest  interface. The method signature is as follows:

 public boolean authenticate(HttpServletResponse response) throws IOException,ServletException

This method is one of the  examples of programmatic security (login, in particular) in Java EE 6. It can be used as an alternative to the <auth-constraint>. When used in a servlet or a JSP, it forces authentication, using the login-mechanism specified in web.xml, even if no security-constraint element is specified in the web.xml.

After a call to authenticate succeeds, the user credentials are validated and the following methods provide the expected results:

(i) getRemoteUser() - the name of the remote user associated with the request,

(ii) isUserInRole() - determines if the remote user (that is, the caller) associated with the request is in a specified security role - returns true after a successful authenticate, provided the role is specified.

(iii) getUserPrincipal()  - method determines the principal name of the remote user (that is, the caller) and returns a object corresponding to the remote user.

The advantage of using the authenticate method is that it provides the flexibility to login in dynamically combined with the ability to be used with the configured  login-mechanism like BASIC. Here is a sample application that illustrates the authenticate method. On deploying the war file and accessing the servlet (http://<server-name>:<port-number>/testsam/test , BASIC authentication is forced by the  container, since the call to authenticate() is made in the service method of the servlet.

New Security Features in Glassfish v3 (Java EE 6) - Part I

The http-method-omission element

Now that Java EE 6 has been officially released and Glassfish v3 (the first application server that supports Java EE 6) is shipped along with it,  it might be beneficial to see what are the new features (in security) that are added to Java EE 6 and are implemented in Glassfish v3. The servlet 3.0 specification brings in many new features of security. This post illustrates one feature - the new http-method-omission element.

As many developers working in web security would know, currently, to protect a set of resources with an auth-constraint, the security-constraint element is added to the portable deployment descriptor (the web.xml). 

For instance in Java EE 5,



the above element indicates that the  resource referenced by the url pattern /test.jsp, when accessed by all the http-methods except GET  , should be constrained to be viewed only by authenticated users belonging to the role dev. Please note that the security constraint does not apply for  the http-method GET, but only for the other methods (POST, HEAD, PUT, etc).

In Java EE 6, there is an additional facility - http-method-omission, by which one could specify the methods that are omitted from the constraint.

For instance, the above security-constraint element could be re-written as :



which means that the auth-constraint for the resource accessible by the url-pattern /test.jsp is applicable for all methods except GET. This is a simpler alternative of providing the constraint methods.

Here is another example web-application that uses the  http-method-omission element. As can be observed in the web.xml, there are two security-constraint elements. In the first one, all the methods except POST are precluded from  accessing the resource. In the second constraint, only GET and POST are allowed conditional access to the same resource. The combined effect of the constraints is that, only POST is allowed conditional access to the resource.

A single web-resource-collection element cannot have both http-method and http-method-omission elements. In those cases,  distinct   web-resource-collection elements under distinct security-constraint elements must be provided. Whether or not a given  http-method is applicable for an auth-constraint is  obtained as per the algorithm defined in the spec:

" HTTP method is said to occur within a web- resource-collection when no HTTP methods are named in the collection, or the collection specifically names the HTTP method in a contained http-method element, or the collection contains one or more http-method-omission elements, none of which names the HTTP method...."

Please refer to Chapter 13, Sec 8.1 of the Servlet 3.0 spec for more details on the rules for combined security-constraints.

Friday Dec 04, 2009

Drawing TrueType Fonts Using Java

The various fonts that are displayed in any raster image of a display device or a printer requires a font engine to render them. TrueType fonts are a specific kind of font format that  are widely used by Mac and Windows machines. These are  binary files with the extension .ttf and could be converted to human-readable files using utilities like fonttools (in Ubuntu). A typcal human-readable truetype font file would look like an XML file with data to draw all the characters of a font. The is XML file could be parsed and drawn as an image output using Java's Graphics2D API.

 Any  character (or the glyph in broader  terms) to be rendered is represented as a set of contours . Each contour is a path formed by straight lines and Bezier curves, that are in turn connected by a set of points in the x-y co-ordinate space (read as raster space for the display). In addition to the x and y co-ordinates, the points also have a boolean value indicating if the points are either on-curve or off-curve. An on-curve point is part of the contour while the off curve point is a control point of the Bezier curve. A single control point indicates a quadratic Bezier curve while two control points indicate a cubic Bezier curve.

To draw the glyph using Java, the Graphics 2D API (java.awt.\*) could be used. Each point is represented using java.awt.geom.Point2D.  The contour is represented using java.awt.geom.GeneralPath  and the lines and Bezier curves are drawn using the methods lineTo(), quadTo() and curveTo() to represent straight lines, quadratic and cubic Bezier curves respectively.

 Here are the code snippets for the methods:

private static void drawLine(GeneralPath.Double path, Point2D point1, Point2D point2)   {

      path.moveTo(point1.getX() , point1.getY());          

      path.lineTo(point2.getX(), point2.getY());

    private static void drawBezQuadCurve(GeneralPath.Double path, Point2D point1, Point2D controlPoint, Point2D point2) {

path.moveTo(point1.getX() , point1.getY());  

           path.quadTo(controlPoint.getX() , controlPoint.getY() , point2.getX() , point2.getY() );

    private static void drawBezCubicCurve(GeneralPath.Double path, Point2D point1, Point2D ctrlPt1, Point2D ctrlPt2, Point2D point2) {

         path.moveTo(point1.getX() , point1.getY());   

         path.curveTo(ctrlPt1.getX() , ctrlPt1.getY() , ctrlPt2.getX() , ctrlPt2.getY() , point2.getX() , point2.getY());

A contour is constructed from this path using java.awt.geom.Area  . The different contours of a particular glyph are eXlusive ORed before they are filled to provide an exact replica of the font glyph:

            if (contourArea == null) {
                contourArea = new Area(glyfPath);
            } else {
                contourArea.exclusiveOr(new Area(glyfPath));


The algorithm for drawing the glyph must be able to clearly distinguish the lines, quadratic and cubic Bezier curves and draw them accordingly. 

Saturday Mar 21, 2009

The Source is Out There...

Having worked for a couple of years  now in the open source software realm, I guess it would be worthwhile to key down my reminiscences, and with the Open Source Mela Blogging Contest instigating a reason to write, here are some nuggets of what I consider my experience with the open source software . 

It would do this post better justice if initially,  I speak-not from an open-source software developer's perspective...So let me impersonate someone who spends their free time trying to hack some written code or write some hackneyed code for the benefit of the body and soul or at times for the larger benefit of the brethren. What  would this kind of passion-driven programmer turn to at first attempt, for his software needs ranging from an IDE to a server to any framework? Free open source software or premium paid secret sauce software? Its clearly the former..And if that free-lance  software developer is reasonably good at what he does, he is likely to produce another innovative piece of open source software , exploring the existing ones and fitting a few right ones in the right places..For this precise reason - freedom to innovate, open source software is the exact sense of the word..

To the astute novice programmer,  the code that is open is a free practical tutorial not just for familiarizing himself with  "professional" software, but also clarifying issues, participating in the community and contributing more to the existing source. So the student community is  likely to get more familiar with the open source software while in school, and if old habits do die hard, the students are likely to stay in touch with these when they graduate to professional programmers. So, open source software does have the pedagogical edge too..

To the open-source software developer,  community participation in terms of issues and forum questions not only help in free testing of the "unexplored areas in unknown avenues", but also to open that normally closed perspective to new suggestions..And of course, it helps in making new interesting friends..Trust me :)

So all said and done, what of the revenue factor?How valuable or vulnerable are the original software developers to the open-source software product which has a strong community base? These are some hard questions which require strategic answers that might make or break the open-source software product. But being open-source is like being infectious..It has to spread  across vendors, sooner or later, unless of course, you are bolstered by a strong immune system. So, if the  cardinal factors which  might help such an open-source product survive the test of revenue and the test of time are decisively addressed, this does seem the way for the industry to go...The source is out there..Go, Seek it!!

Tuesday Mar 10, 2009

VirtualBox in LAN

If you would like to make a Linux virtual machine (created using say Sun's VirtualBox)  connect to your LAN to which the host machine is a part of, you could follow these steps:

(0) Create the virtual machine and install the guest OS (I installed Ubuntu).

(1) Install bridge-utils and uml-utilities on the guest OS:

         sudo apt-get install bridge-utils uml-utilities

(2) Edit /etc/network/if-pre-up.d/uml-utilities to change:

     chown root:uml-net /dev/net/tun

      to      chown root:vboxusers /dev/net/tun

(3) Change the VirtualMachine settings from NAT (the default) to Host Interface in the Network settings tab of the GUI.

(4) Restart the networking service

     sudo /etc/init.d/networking restart

After this, the virtual  machine can be accessed from any other machine on the LAN using ssh or vnc if these services are available on the guest OS. For more advanced configuration including TUN/TAP settings, this link might be useful.

Thursday Jan 08, 2009

Modularized OSGi Custom Realms in Glassfish v3

The Open Services Gateway Initiative (OSGi) defines an architecture for developing and deploying modular applications and libraries. Since Glassfish v3 is a modular, embeddable and an OSGi compliant  server, custom realms that are built based on the OSGi framework can be easily integrated and configured with GF v3.This facilitates the creation and configuration of a custom realm without any server restart.

 To be recognized as a valid custom realm  OSGi module, in addition to the OSGi mandated structure, the custom realm  should include the following:

i)The Realm class should include the @Service annotation, with the name attribute referring to the name of the custom realm to be configured:


where @Service is a hk2-specific annotation.

ii) There should be a file named  inside META-INF/services directory of the module archive file. The file should specify the fully qualified name of the Custom Login Module class as in:


A sample OSGi custom realm module can be downloaded from here. On dropping this file in <GF-HOME>/autodeploy-bundles directory, the module should be loaded. Do make sure   that the <GF-HOME>/<DOMAIN-DIR>/login.conf file has an entry for the jaas-context value, referring to the Module implementation class. This entry can be dynamically added to login.conf(before creating the realm). (This post provides a detailed description on creating a custom realm for GF.)

The realm can now be created from the admin console (name matching the service name specified in the Realm class). This should initialize the realm. No server restart required. On deploying and accessing an application utilizing this realm, the Login module should be initialized as well.This feature works with the latest GF v3 trunk installation.




« April 2014