Friday Feb 05, 2010

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

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 java.security.Principal 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.

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,

   <security-constraint>
        <display-name>WebConstraint</display-name>
        <web-resource-collection>
            <web-resource-name>test</web-resource-name>
            <description/>
            <url-pattern>/test.jsp</url-pattern>
            <http-method>POST</http-method>
            <http-method>HEAD</http-method>
            <http-method>PUT</http-method>
            <http-method>OPTIONS</http-method>
            <http-method>TRACE</http-method>
            <http-method>DELETE</http-method>

        </web-resource-collection>
        <auth-constraint>
            <description/>
            <role-name>dev</role-name>
         </auth-constraint>
   </security-constraint>

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 :

<security-constraint>
        <display-name>WebConstraint</display-name>
        <web-resource-collection>
            <web-resource-name>test</web-resource-name>
            <description/>
            <url-pattern>/test.jsp</url-pattern>
            <http-method-omission>GET</http-method-omission>

        </web-resource-collection>
        <auth-constraint>
            <description/>
            <role-name>dev</role-name>
         </auth-constraint>
   </security-constraint>

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:

"...an 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

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

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 priceless...in 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

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

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:

@Service(name="SampleRealm")

where @Service is a hk2-specific annotation.

ii) There should be a file named javax.security.auth.spi.LoginModule  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:

com.samplerealm.SampleLoginModule

A sample OSGi custom realm module can be downloaded from here. On dropping this file in <GF-HOME>/<DOMAIN-DIR>/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.



Monday Dec 29, 2008

Glassfish  provides support for Custom Realms and Custom Login Modules that are based on the JAAS framework. This post explains how to write a simple Realm class and its corresponding LoginModule, configure them with an illustration of a simple web application that uses this realm.

Custom Realm

The Custom Realm should extend com.sun.appserv.security.AppservRealm. The Realm class is basically meant to provide user and group-related information. The methods to be implemented are

i) public void init(Properties properties )throws BadRealmException, NoSuchRealmException

This method is invoked during server startup when the realm is initially loaded.  The realm can do any initialization it needs in this method. The Properties is a set of key-value pairs configured while creating the Realm and are present in domain.xml. Among the other custom properties, there is a property jaas-context (which is explained later in this post). This property should be set using the call setProperty method implemented in the parent class. If the method returns without throwing an exception, the Enterprise Server assumes that the realm is ready to service authentication requests. If an exception is thrown, the realm is disabled.

ii) public String getAuthType() - This method returns a descriptive string representing the type of authentication done by this realm.

iii) public Enumeration getGroupNames(String user) throws InvalidOperationException, NoSuchUserException -
This method returns the group names the user belongs to as an Enumeration of Strings.

Custom LoginModule

The Custom LoginModule should extend com.sun.appserv.security.AppservPasswordLoginModule. This class should override the method

abstract protected void authenticateUser() throws LoginException

This method performs the actual custom authentication, by either using a database, or LDAP or a file or even a simple Hashtable as illustrated in the attached sample code. The custom login module must not implement any of the other methods, such as login(), logout(), abort(), commit(), or initialize(). Default implementations are provided in AppservPasswordLoginModule which hook into the Enterprise Server infrastructure.

The custom login module can access the following protected object fields, which it inherits from AppservPasswordLoginModule. These contain the user name, password of the user to be authenticated and the currentRealm class.

protected String _username;

protected String _password;

protected com.sun.enterprise.security.auth.realm.Realm  _currentRealm;

The authenticateUser() method should end with a call to the commitUserAuthentication(String[] authenticatedGroupList) method where the authenticatedGroupList is the list of groups the user belongs to.

As can be observed, the realm class is isolated from the LoginModule. The Realm is capable of capturing arbitrary configuration information and can help in obtaining the Group information. The Group information from the Realm can be  populated into the authenticated JAAS subject during commit() phase following a  successful LoginContext.login() call on the  authentication module. This populated group information is then used by the container in its authorization policy decisions.

Attached here is the source code of a simple sample realm class and the custom module. In this example, the Realm class stores the user-group information in a hashtable. The LoginModule class stores the user-password information in a hashtable and performs authentication. It obtains the authenticatedGroupList from the Realm class' getGroups(username) method.

To test this sample(it works with both GF v2 and v3), download and install Glassfish v3 from here, drop the binaries of this realm and custom module in <GF-ROOT>/domains/domain1/lib/, start the server and create the realm using the Admin console. The realm classname should be specified as com.samplerealm.SampleRealm.

An additional realm property jaas-context should be specified to say sampleRealm. This value should refer to the SampleLoginModule class in the

<GF-ROOT>/domains/domain1/config/login.conf

file as follows:

sampleRealm {
       com.samplerealm.SampleLoginModule required;
};

where sampleRealm refers to the value defined in the jaas-context property.

As can be seen from the source files, the users configured in this realm are userA, userB whose corresponding passwords are abc123, xyz123. userA has been configured in the group devGroup, while userB belongs to testGroup. To test this realm, this web-application can be used.

Observe that the web.xml of the web-app contains the following :

<login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>SampleRealm</realm-name>
     </login-config>

where  SampleRealm in the <login-conf><realm-name> element points to the name of the configured Realm as can be seen in the server's domain.xml

        <auth-realm classname="com.samplerealm.SampleRealm" name="SampleRealm">
          <property name="jaas-context" value="sampleRealm"></property>
        </auth-realm>

To access the web-app using the group names of the user, the following mapping between the role and group is required in sun-web.xml:

  <security-role-mapping>
    <role-name>tester</role-name>
    <group-name>devgroup</group-name>
  </security-role-mapping>

where the role-name matches the configured role in the auth-constraint of web.xml

        <auth-constraint>
            <description/>
            <role-name>tester</role-name>
         </auth-constraint>

and group-name is the corresponding group the user belongs to as defined in the custom realm class. So if the application is accessed using the user/password: userA/abc123, the user is authorized to view the pages, since he belongs to the devGroup, but not userB/xyz123 (who belongs to testGroup).


Monday Sep 01, 2008

    The OpenPortal WSRP Consumer has been integrated with Liferay Portal, and is available in the stable and community builds of WebSynergy. This blog post would illustrate the basic features of this integration. All the features that are available with the Sun's implementation of WSRP 2.0 with the OpenPortal Portlet Container have been integrated with Liferay and consequently with WebSynergy as well. The admin portlets now have the modified look and feel. Here are some screenshots showcasing the Consumer Admin Portlet in WebSynergy.

The WSRP Consumer Admin Portlet:

LR Consumer Admin Portlet

Creating a Consumer:


Viewing the Details of a Consumer: 


As can be observed, this admin portlet supports the major functionalities in WSRP 2.0 Consumer creation - OutOfBand Registration (using RegistrationHandle), Leasing, Registration Properties amongst others. Producer Integration and Producer Admin Portlet are expected to be integrated with Liferay  in the next stable release of WebSynergy.


Thursday Aug 07, 2008

Recently I had the privilege of corrupting the MBR of my laptop. The modus operandi - I formatted the Solaris partition from my Windows boot. That consequently corrputed the grub and the Master Boot Record. Only later did I discover that a lot of people I knew had done this quite frequently. A typical solution for this problem was to boot from a live Windows CD, launch the Revocery Console, and run the fixmbr utility. (For Windows versions previous to 2000, the fdisk utility could be used as well, but for the newer versions, this utility was scrapped, since Recovery Console was provided).

An atypical but useful solution would be to boot Windows from any live CD (I used Belenix), boot Windows from the command prompt, and run this Mbrfix utility. You don't need to have a Windows Live CD or Recovery Console. This atypical solution was provided by an extremely resourceful and benevolent colleague, and it worked.

Tuesday Jun 17, 2008

WSRP 2.0 offers Leasing of Portlets as part  of the specification. Leasing is the process by which a Consumer registers with a Producer for a specified time period, after which the Consumer Registration is rendered invalid. Lifetime is an optional parameter in the Registration offered by V2 producers. The OpenPortal WSRP project (Sun's open source implementation of WSRP ) has implemented this feature using the Open Source Portlet Container 2.0 . Check this wiki page for more information on portlet leasing.

A quick guide to Leasing with Open WSRP and PC 2.0 

1. Download and install PC 2.0 and WSRP  . For instructions on download, refer to the install instructions

2. Create a V2 producer (supporting Inband Registration) using the Producer Admin Portlet. Publish a few portlets and enable the Producer.

3. Create a V2 consumer. Check the Lifetime Supplied checkbox. Specify the Valid No of Days, Hours and Minutes, say 0,0,15. This means that the Registration is valid only for the next 15 minutes. Click the Consumer to view the time until which Registration is valid.

4. Create  a remote portlet in a window for the Consumer. Check the remote portlet before and after the Registration cut -off time. After the lifetime expires, the remote portlet would not be rendered.

Lifetime


Monday May 19, 2008

To get to know the details of a site, like the operating system, hardware, server, IP addresses of the servers among others, check out Netcraft

For instance, here are the details of this site:  http://blogs.sun.com/nithya

unknown Sun-Java-System-Web-Server/7.0 19-May-2008 72.5.124.56  SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 16-Apr-2008 72.5.124.56  SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 18-Feb-2008 72.5.124.56  SUN MICROSYSTEMS
unknown Sun-Java-System-Web-Server/7.0 17-Feb-2008 72.5.124.56  SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 15-Feb-2008 72.5.124.56  SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 16-Jan-2008 72.5.124.56  SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 4-Nov-2007 72.5.124.56  SUN MICROSYSTEMS
unknown Sun-Java-System-Web-Server/7.0 25-Oct-2007 72.5.124.56  SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 14-Oct-2007 72.5.124.56  SUN MICROSYSTEMS
Solaris 9/10 Sun-Java-System-Web-Server/7.0 13-Oct-2007 72.5.124.56  SUN MICROSYSTEMS

 

 

Sunday May 18, 2008

 Personal Branding is a new-age market mantra, synonymous with marketing yourself in a cut-throat competitive world. Here's a very interesting article on how to create a personal brand for yourself.

Am making the highlights redundant: Steps for a successfully branded you:
 

  1. Know what you want: Identify what you want, and start walking toward it.
  2. Be able to articulate what you do: When someone asks what you do, answer them immediately with a clear, concise, and confident response.
  3. Elevator pitch: Be able to describe who you are and what you do in the time it takes to ride an elevator.
  4. Be positive: Be positive.
  5. Business card: A 3x5 piece of paper or mini-CD that has your personal contact information clearly printed on it.
  6. Have a blog / Website / MySpace, or other online presence: Get your brand online.
  7. Multiple e-mail addresses: Get more than one e-mail address.
  8. Phone: Get a phone.
  9. Signature: Your signature is who you are, your title, and your contact information. You should put this on everything you touch.
  10. Logo: A visual image that positively identifies your brand.
  11. Personal goals: Set goals for yourself that help you reach what you want.
  12. More than one resume: Customize your resume to the potential employer or client.
  13. Mentor: Find a guru and have them teach you.
  14. Networking outlets / contacts: Continually develop your network by attending industry meetings and conferences.
  15. Wardrobe style: When you are going to be near people who you wish to sell your brand to, dress to impress.
  16. Multiple IM accounts: Get more than one IM account.
  17. Alias: Obtain a positive nickname.
  18. Mantra: Collect sayings that enforce your brand.
  19. Speaking and PowerPoint template: Speak about what you do and have a hot-looking PowerPoint template to show.
  20. Passion: Love what you do.

 

 

Thursday May 15, 2008

Here is a list of web service APIs offered by popular companies that are available for integration with customized applications. Popular ones include the services offered by Yahoo, Google, Amazon, Remember The Milk, Second Life amongst others...

 

Tuesday May 13, 2008

Firebug is the browser debugger, available as a firefox add-on. Client-side debugging, which becomes particularly important in Ajax applications with extensive JavaScript, is made much simpler with this add-on feature. Some of the features offered are 

1. Http Monitoring and Inspection - The HTTP Requests, Responses, Headers, Response times (along with their Ajax XMLHttpRequest counterparts) can be viewed and monitored.

2. Breakpoint Debugging - Breakpoints can be set and the code flow can be stepped in , stepped out or stepped over.

3. Console Logging - In firefox browsers, an implicit object called console is made available, Log statements can be inserted using console.log("Logged")

4. DOM Inspection - The HTTP DOM tree can be inspected down to the smallest elements

5. Profiling - console.profile() and console.profileEnd() methods could be used to analyse the time elapses within code blocks..

Firebug can be opened in the same browser tab as the HTML page or a different tab. Its as simple to use as it sounds too :). Open Firebug (preferably in the same browser tab), explore the tabs, go to say script tab, the entire Javascript of the HTML page is made available here. Set the breakpoints, and refresh the browser. The requests, headers can be seen and  the debugging cursor stops at the first breakpoint. Step over, step in, step out , monitor and inspect the Javascript objects and HTML objects. If you are still stuck, insert log statements and check them in the console...Go, debug the bugs..

 With Firebug, client side debugging seems to have truly evolved...

This blog copyright 2010 by Nithya Subramanian