Chapter 8. Security on JBoss

J2EE Security Configuration and Architecture

Security is a fundamental part of any enterprise application. You need to be able to restrict who is allowed to access your applications and control what operations application users may perform. The J2EE specifications define a simple role-based security model for EJBs and web components. The JBoss component framework that handles security is the JBossSX extension framework. The JBossSX security extension provides support for both the role-based declarative J2EE security model and integration of custom security via a security proxy layer. The default implementation of the declarative security model is based on Java Authentication and Authorization Service (JAAS) login modules and subjects. The security proxy layer allows custom security that cannot be described using the declarative model to be added to an EJB in a way that is independent of the EJB business object. Before getting into the JBoss security implementation details, we will review EJB and servlet specification security models, as well as JAAS to establish the foundation for these details.

8.1. J2EE Declarative Security Overview

The J2EE security model declarative in that you describe the security roles and permissions in a standard XML descriptor rather than embedding security into your business component. This isolates security from business-level code because security tends to be more a function of where the component is deployed than an inherent aspect of the component's business logic. For example, consider an ATM component that is to be used to access a bank account. The security requirements, roles and permissions will vary independently of how you access the bank account, based on what bank is managing the account, where the ATM is located, and so on.

Securing a J2EE application is based on the specification of the application security requirements via the standard J2EE deployment descriptors. You secure access to EJBs and web components in an enterprise application by using the ejb-jar.xml and web.xml deployment descriptors. The following sections look at the purpose and usage of the various security elements.

8.1.1. Security References

Both EJBs and servlets can declare one or more security-role-ref elements as shown in Figure 8.1, “The security-role-ref element”. This element declares that a component is using the role-name value as an argument to the isCallerInRole(String) method. By using the isCallerInRole method, a component can verify whether the caller is in a role that has been declared with a security-role-ref/role-name element. The role-name element value must link to a security-role element through the role-link element. The typical use of isCallerInRole is to perform a security check that cannot be defined by using the role-based method-permissions elements.

The security-role-ref element

Figure 8.1. The security-role-ref element

Example 8.1, “An ejb-jar.xml descriptor fragment that illustrates the security-role-ref element usage.” shows the use of security-role-ref in an ejb-jar.xml.

Example 8.1. An ejb-jar.xml descriptor fragment that illustrates the security-role-ref element usage.

<!-- A sample ejb-jar.xml fragment -->
<ejb-jar>
  <enterprise-beans>
    <session>
      <ejb-name>ASessionBean</ejb-name>
      ...
      <security-role-ref>
          <role-name>TheRoleICheck</role-name>
          <role-link>TheApplicationRole</role-link>
      </security-role-ref>
    </session>
  </enterprise-beans>
  ...
</ejb-jar>

Example 8.2, “An example web.xml descriptor fragment that illustrates the security-role-ref element usage.” shows the use of security-role-ref in a web.xml.

Example 8.2. An example web.xml descriptor fragment that illustrates the security-role-ref element usage.

<web-app>
    <servlet>
        <servlet-name>AServlet</servlet-name>
        ...
        <security-role-ref>
            <role-name>TheServletRole</role-name>
            <role-link>TheApplicationRole</role-link>
        </security-role-ref>
    </servlet>
    ...
</web-app>

8.1.2. Security Identity

An EJB has the capability to specify what identity an EJB should use when it invokes methods on other components using the security-identity element, shown in Figure 8.2, “The security-identity element”

The security-identity element

Figure 8.2. The security-identity element

The invocation identity can be that of the current caller, or it can be a specific role. The application assembler uses the security-identity element with a use-caller-identity child element to indicate that the current caller's identity should be propagated as the security identity for method invocations made by the EJB. Propagation of the caller's identity is the default used in the absence of an explicit security-identity element declaration.

Alternatively, the application assembler can use the run-as/role-name child element to specify that a specific security role given by the role-name value should be used as the security identity for method invocations made by the EJB. Note that this does not change the caller's identity as seen by the EJBContext.getCallerPrincipal() method. Rather, the caller's security roles are set to the single role specified by the run-as/role-name element value. One use case for the run-as element is to prevent external clients from accessing internal EJBs. You accomplish this by assigning the internal EJB method-permission elements that restrict access to a role never assigned to an external client. EJBs that need to use internal EJB are then configured with a run-as/role-name equal to the restricted role. The following descriptor fragment that illustrates security-identity element usage.

<!-- A sample ejb-jar.xml fragment -->
<ejb-jar>
    <enterprise-beans>
        <session>
            <ejb-name>ASessionBean</ejb-name>
            <!-- ... -->
            <security-identity>
                <use-caller-identity/>
            </security-identity>
        </session>
        <session>
            <ejb-name>RunAsBean</ejb-name>
            <!-- ... -->
            <security-identity>
                <run-as>
                    <description>A private internal role</description>
                    <role-name>InternalRole</role-name>
                </run-as>
            </security-identity>
        </session>
    </enterprise-beans>
    <!-- ... -->
</ejb-jar>

When you use run-as to assign a specific role to outgoing calls, JBoss associates a principal named anonymous. If you want another prinicipal to be associated with the call, you need to associate a run-as-principal with the bean in the jboss.xml file. The following fragment associates a principal named internal with RunAsBean from the prior example.

<session>
    <ejb-name>RunAsBean</ejb-name>
    <security-identity>
        <run-as-principal>internal</run-as-principal>
    </security-identity>
</session>

The run-as element is also available in servlet definitions in a web.xml file. The following example shows how to assign the role InternalRole to a servlet:

<servlet>
    <servlet-name>AServlet</servlet-name>
    <!-- ... -->
    <run-as> 
        <role-name>InternalRole</role-name>
    </run-as>
</servlet>

Calls from this servlet will be associated with the anonymous principal. The run-as-principal element is available in the jboss-web.xml file to assign a specific principal to go along with the run-as role. The following fragment shows how to associate a principal named internal to the servlet in the prior example.

<servlet>
    <servlet-name>AServlet</servlet-name>
    <run-as-principal>internal</run-as-principal>
</servlet>

8.1.3. Security roles

The security role name referenced by either the security-role-ref or security-identity element needs to map to one of the application's declared roles. An application assembler defines logical security roles by declaring security-role elements. The role-name value is a logical application role name like Administrator, Architect, SalesManager, etc.

The J2EE specifications note that it is important to keep in mind that the security roles in the deployment descriptor are used to define the logical security view of an application. Roles defined in the J2EE deployment descriptors should not be confused with the user groups, users, principals, and other concepts that exist in the target enterprise's operational environment. The deployment descriptor roles are application constructs with application domain-specific names. For example, a banking application might use role names such as BankManager, Teller, or Customer.

The security-role element

Figure 8.3. The security-role element

In JBoss, a security-role element is only used to map security-role-ref/role-name values to the logical role that the component role references. The user's assigned roles are a dynamic function of the application's security manager, as you will see when we discuss the JBossSX implementation details. JBoss does not require the definition of security-role elements in order to declare method permissions. However, the specification of security-role elements is still a recommended practice to ensure portability across application servers and for deployment descriptor maintenance. Example 8.3, “An ejb-jar.xml descriptor fragment that illustrates the security-role element usage.” shows the usage of the security-role in an ejb-jar.xml file.

Example 8.3. An ejb-jar.xml descriptor fragment that illustrates the security-role element usage.

<!-- A sample ejb-jar.xml fragment -->
<ejb-jar>
    <!-- ... -->
    <assembly-descriptor>
        <security-role>
            <description>The single application role</description>
            <role-name>TheApplicationRole</role-name>
        </security-role>
    </assembly-descriptor>
</ejb-jar>

Example 8.4, “An example web.xml descriptor fragment that illustrates the security-role element usage.” shows the usage of the security-role in an web.xml file.

Example 8.4. An example web.xml descriptor fragment that illustrates the security-role element usage.

<!-- A sample web.xml fragment -->
<web-app>
    <!-- ... -->
    <security-role>
        <description>The single application role</description>
        <role-name>TheApplicationRole</role-name>
    </security-role>
</web-app>

8.1.4. EJB method permissions

An application assembler can set the roles that are allowed to invoke an EJB's home and remote interface methods through method-permission element declarations.

The method-permissions element

Figure 8.4. The method-permissions element

Each method-permission element contains one or more role-name child elements that define the logical roles that are allowed to access the EJB methods as identified by method child elements. You can also specify an unchecked element instead of the role-name element to declare that any authenticated user can access the methods identified by method child elements. In addition, you can declare that no one should have access to a method that has the exclude-list element. If an EJB has methods that have not been declared as accessible by a role using a method-permission element, the EJB methods default to being excluded from use. This is equivalent to defaulting the methods into the exclude-list.

The method element

Figure 8.5. The method element

There are three supported styles of method element declarations.

The first is used for referring to all the home and component interface methods of the named enterprise bean:

<method>
    <ejb-name>EJBNAME</ejb-name>
    <method-name>*</method-name>
</method>

The second style is used for referring to a specified method of the home or component interface of the named enterprise bean:

<method>
    <ejb-name>EJBNAME</ejb-name>
    <method-name>METHOD</method-name>
                </method>

If there are multiple methods with the same overloaded name, this style refers to all of the overloaded methods.

The third style is used to refer to a specified method within a set of methods with an overloaded name:

<method>
    <ejb-name>EJBNAME</ejb-name>
    <method-name>METHOD</method-name>
    <method-params>
        <method-param>PARAMETER_1</method-param>
        <!-- ... -->
        <method-param>PARAMETER_N</method-param>
    </method-params>
</method>

The method must be defined in the specified enterprise bean's home or remote interface. The method-param element values are the fully qualified name of the corresponding method parameter type. If there are multiple methods with the same overloaded signature, the permission applies to all of the matching overloaded methods.

The optional method-intf element can be used to differentiate methods with the same name and signature that are defined in both the home and remote interfaces of an enterprise bean.

Example 8.5, “An ejb-jar.xml descriptor fragment that illustrates the method-permission element usage.” provides complete examples of the method-permission element usage.

Example 8.5. An ejb-jar.xml descriptor fragment that illustrates the method-permission element usage.

<ejb-jar>
    <assembly-descriptor>
        <method-permission>
            <description>The employee and temp-employee roles may access any
                method of the EmployeeService bean </description>
            <role-name>employee</role-name>
            <role-name>temp-employee</role-name>
            <method>
                <ejb-name>EmployeeService</ejb-name>
                <method-name>*</method-name>
            </method>
        </method-permission>
        <method-permission>
            <description>The employee role may access the findByPrimaryKey,
                getEmployeeInfo, and the updateEmployeeInfo(String) method of
                the AardvarkPayroll bean </description>
            <role-name>employee</role-name>
            <method>
                <ejb-name>AardvarkPayroll</ejb-name>
                <method-name>findByPrimaryKey</method-name>
            </method>
            <method>
                <ejb-name>AardvarkPayroll</ejb-name>
                <method-name>getEmployeeInfo</method-name>
            </method>
            <method>
                <ejb-name>AardvarkPayroll</ejb-name>
                <method-name>updateEmployeeInfo</method-name>
                <method-params>
                    <method-param>java.lang.String</method-param>
                </method-params>
            </method>
        </method-permission>
        <method-permission>
            <description>The admin role may access any method of the
                EmployeeServiceAdmin bean </description>
            <role-name>admin</role-name>
            <method>
                <ejb-name>EmployeeServiceAdmin</ejb-name>
                <method-name>*</method-name>
            </method>
        </method-permission>
        <method-permission>
            <description>Any authenticated user may access any method of the
                EmployeeServiceHelp bean</description>
            <unchecked/>
            <method>
                <ejb-name>EmployeeServiceHelp</ejb-name>
                <method-name>*</method-name>
            </method>
        </method-permission>
        <exclude-list>
            <description>No fireTheCTO methods of the EmployeeFiring bean may be
                used in this deployment</description>
            <method>
                <ejb-name>EmployeeFiring</ejb-name>
                <method-name>fireTheCTO</method-name>
            </method>
        </exclude-list>
    </assembly-descriptor>
</ejb-jar>

8.1.5. Web Content Security Constraints

In a web application, security is defined by the roles that are allowed access to content by a URL pattern that identifies the protected content. This set of information is declared by using the web.xml security-constraint element.

The security-constraint element

Figure 8.6. The security-constraint element

The content to be secured is declared using one or more web-resource-collection elements. Each web-resource-collection element contains an optional series of url-pattern elements followed by an optional series of http-method elements. The url-pattern element value specifies a URL pattern against which a request URL must match for the request to correspond to an attempt to access secured content. The http-method element value specifies a type of HTTP request to allow.

The optional user-data-constraint element specifies the requirements for the transport layer of the client to server connection. The requirement may be for content integrity (preventing data tampering in the communication process) or for confidentiality (preventing reading while in transit). The transport-guarantee element value specifies the degree to which communication between the client and server should be protected. Its values are NONE, INTEGRAL, and CONFIDENTIAL. A value of NONE means that the application does not require any transport guarantees. A value of INTEGRAL means that the application requires the data sent between the client and server to be sent in such a way that it can't be changed in transit. A value of CONFIDENTIAL means that the application requires the data to be transmitted in a fashion that prevents other entities from observing the contents of the transmission. In most cases, the presence of the INTEGRAL or CONFIDENTIAL flag indicates that the use of SSL is required.

The optional login-config element is used to configure the authentication method that should be used, the realm name that should be used for rhw application, and the attributes that are needed by the form login mechanism.

The login-config element

Figure 8.7. The login-config element

The auth-method child element specifies the authentication mechanism for the web application. As a prerequisite to gaining access to any web resources that are protected by an authorization constraint, a user must have authenticated using the configured mechanism. Legal auth-method values are BASIC, DIGEST, FORM, and CLIENT-CERT. The realm-name child element specifies the realm name to use in HTTP basic and digest authorization. The form-login-config child element specifies the log in as well as error pages that should be used in form-based login. If the auth-method value is not FORM, then form-login-config and its child elements are ignored.

As an example, the web.xml descriptor fragment given in Example 8.6, “ A web.xml descriptor fragment which illustrates the use of the security-constraint and related elements.” indicates that any URL lying under the web application's /restricted path requires an AuthorizedUser role. There is no required transport guarantee and the authentication method used for obtaining the user identity is BASIC HTTP authentication.

Example 8.6.  A web.xml descriptor fragment which illustrates the use of the security-constraint and related elements.

<web-app>
    <!-- ... -->
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Secure Content</web-resource-name>
            <url-pattern>/restricted/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>AuthorizedUser</role-name>
        </auth-constraint>
        <user-data-constraint>
            <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
    </security-constraint>
    <!-- ... -->
    <login-config>
        <auth-method>BASIC</auth-method>
        <realm-name>The Restricted Zone</realm-name>
    </login-config>
    <!-- ... -->
    <security-role>
        <description>The role required to access restricted content </description>
        <role-name>AuthorizedUser</role-name>
    </security-role>
</web-app>

8.1.6. Enabling Declarative Security in JBoss

The J2EE security elements that have been covered so far describe the security requirements only from the application's perspective. Because J2EE security elements declare logical roles, the application deployer maps the roles from the application domain onto the deployment environment. The J2EE specifications omit these application server-specific details. In JBoss, mapping the application roles onto the deployment environment entails specifying a security manager that implements the J2EE security model using JBoss server specific deployment descriptors. The details behind the security configuration are discussed in Section 8.3, “The JBoss Security Model”.

8.2. An Introduction to JAAS

The JBossSX framework is based on the JAAS API. It is important that you understand the basic elements of the JAAS API to understand the implementation details of JBossSX. The following sections provide an introduction to JAAS to prepare you for the JBossSX architecture discussion later in this chapter.

8.2.1. What is JAAS?

The JAAS 1.0 API consists of a set of Java packages designed for user authentication and authorization. It implements a Java version of the standard Pluggable Authentication Module (PAM) framework and compatibly extends the Java 2 Platform's access control architecture to support user-based authorization. JAAS was first released as an extension package for JDK 1.3 and is bundled with JDK 1.4+. Because the JBossSX framework uses only the authentication capabilities of JAAS to implement the declarative role-based J2EE security model, this introduction focuses on only that topic.

JAAS authentication is performed in a pluggable fashion. This permits Java applications to remain independent from underlying authentication technologies and allows the JBossSX security manager to work in different security infrastructures. Integration with a security infrastructure can be achieved without changing the JBossSX security manager implementation. All that needs to change is the configuration of the authentication stack that JAAS uses.

8.2.1.1. The JAAS Core Classes

The JAAS core classes can be broken down into three categories: common, authentication, and authorization. The following list presents only the common and authentication classes because these are the specific classes used to implement the functionality of JBossSX covered in this chapter.

The are the common classes:

  • Subject (javax.security.auth.Subject)

  • Principal (java.security.Principal)

These are the authentication classes:

  • Callback (javax.security.auth.callback.Callback)

  • CallbackHandler (javax.security.auth.callback.CallbackHandler)

  • Configuration (javax.security.auth.login.Configuration)

  • LoginContext (javax.security.auth.login.LoginContext)

  • LoginModule (javax.security.auth.spi.LoginModule)

8.2.1.1.1. The Subject and Principal Classes

To authorize access to resources, applications first need to authenticate the request's source. The JAAS framework defines the term subject to represent a request's source. The Subject class is the central class in JAAS. A Subject represents information for a single entity, such as a person or service. It encompasses the entity's principals, public credentials, and private credentials. The JAAS APIs use the existing Java 2 java.security.Principal interface to represent a principal, which is essentially just a typed name.

During the authentication process, a subject is populated with associated identities, or principals. A subject may have many principals. For example, a person may have a name principal (John Doe), a social security number principal (123-45-6789), and a username principal (johnd), all of which help distinguish the subject from other subjects. To retrieve the principals associated with a subject, two methods are available:

public Set getPrincipals() {...}
public Set getPrincipals(Class c) {...} 

The first method returns all principals contained in the subject. The second method returns only those principals that are instances of class c or one of its subclasses. An empty set is returned if the subject has no matching principals. Note that the java.security.acl.Group interface is a subinterface of java.security.Principal, so an instance in the principals set may represent a logical grouping of other principals or groups of principals.

8.2.1.1.2. Authentication of a Subject

Authentication of a subject requires a JAAS login. The login procedure consists of the following steps:

  1. An application instantiates a LoginContext and passes in the name of the login configuration and a CallbackHandler to populate the Callback objects, as required by the configuration LoginModules.

  2. The LoginContext consults a Configuration to load all the LoginModules included in the named login configuration. If no such named configuration exists the other configuration is used as a default.

  3. The application invokes the LoginContext.login method.

  4. The login method invokes all the loaded LoginModules. As each LoginModule attempts to authenticate the subject, it invokes the handle method on the associated CallbackHandler to obtain the information required for the authentication process. The required information is passed to the handle method in the form of an array of Callback objects. Upon success, the LoginModules associate relevant principals and credentials with the subject.

  5. The LoginContext returns the authentication status to the application. Success is represented by a return from the login method. Failure is represented through a LoginException being thrown by the login method.

  6. If authentication succeeds, the application retrieves the authenticated subject using the LoginContext.getSubject method.

  7. After the scope of the subject authentication is complete, all principals and related information associated with the subject by the login method can be removed by invoking the LoginContext.logout method.

The LoginContext class provides the basic methods for authenticating subjects and offers a way to develop an application that is independent of the underlying authentication technology. The LoginContext consults a Configuration to determine the authentication services configured for a particular application. LoginModule classes represent the authentication services. Therefore, you can plug different login modules into an application without changing the application itself. The following code shows the steps required by an application to authenticate a subject.

CallbackHandler handler = new MyHandler();
LoginContext lc = new LoginContext("some-config", handler);

try {
    lc.login();
    Subject subject = lc.getSubject();
} catch(LoginException e) {
    System.out.println("authentication failed");
    e.printStackTrace();
}
                        
// Perform work as authenticated Subject
// ...

// Scope of work complete, logout to remove authentication info
try {
    lc.logout();
} catch(LoginException e) {
    System.out.println("logout failed");
    e.printStackTrace();
}
                        
// A sample MyHandler class
class MyHandler 
    implements CallbackHandler
{
    public void handle(Callback[] callbacks) throws
        IOException, UnsupportedCallbackException
    {
        for (int i = 0; i < callbacks.length; i++) {
            if (callbacks[i] instanceof NameCallback) {
                NameCallback nc = (NameCallback)callbacks[i];
                nc.setName(username);
            } else if (callbacks[i] instanceof PasswordCallback) {
                PasswordCallback pc = (PasswordCallback)callbacks[i];
                pc.setPassword(password);
            } else {
                throw new UnsupportedCallbackException(callbacks[i],
                                                       "Unrecognized Callback");
            }
        }
    }
}

Developers integrate with an authentication technology by creating an implementation of the LoginModule interface. This allows an administrator to plug different authentication technologies into an application. You can chain together multiple LoginModules to allow for more than one authentication technology to participate in the authentication process. For example, one LoginModule may perform username/password-based authentication, while another may interface to hardware devices such as smart card readers or biometric authenticators.

The life cycle of a LoginModule is driven by the LoginContext object against which the client creates and issues the login method. The process consists of two phases. The steps of the process are as follows:

  • The LoginContext creates each configured LoginModule using its public no-arg constructor.

  • Each LoginModule is initialized with a call to its initialize method. The Subject argument is guaranteed to be non-null. The signature of the initialize method is: public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options).

  • The login method is called to start the authentication process. For example, a method implementation might prompt the user for a username and password and then verify the information against data stored in a naming service such as NIS or LDAP. Alternative implementations might interface to smart cards and biometric devices, or simply extract user information from the underlying operating system. The validation of user identity by each LoginModule is considered phase 1 of JAAS authentication. The signature of the login method is boolean login() throws LoginException. A LoginException indicates failure. A return value of true indicates that the method succeeded, whereas a return valueof false indicates that the login module should be ignored.

  • If the LoginContext's overall authentication succeeds, commit is invoked on each LoginModule. If phase 1 succeeds for a LoginModule, then the commit method continues with phase 2 and associates the relevant principals, public credentials, and/or private credentials with the subject. If phase 1 fails for a LoginModule, then commit removes any previously stored authentication state, such as usernames or passwords. The signature of the commit method is: boolean commit() throws LoginException. Failure to complete the commit phase is indicated by throwing a LoginException. A return of true indicates that the method succeeded, whereas a return of false indicates that the login module should be ignored.

  • If the LoginContext's overall authentication fails, then the abort method is invoked on each LoginModule. The abort method removes or destroys any authentication state created by the login or initialize methods. The signature of the abort method is boolean abort() throws LoginException. Failure to complete the abort phase is indicated by throwing a LoginException. A return of true indicates that the method succeeded, whereas a return of false indicates that the login module should be ignored.

  • To remove the authentication state after a successful login, the application invokes logout on the LoginContext. This in turn results in a logout method invocation on each LoginModule. The logout method removes the principals and credentials originally associated with the subject during the commit operation. Credentials should be destroyed upon removal. The signature of the logout method is: boolean logout() throws LoginException. Failure to complete the logout process is indicated by throwing a LoginException. A return of true indicates that the method succeeded, whereas a return of false indicates that the login module should be ignored.

When a LoginModule must communicate with the user to obtain authentication information, it uses a CallbackHandler object. Applications implement the CallbackHandler interface and pass it to the LoginContext, which forwards it directly to the underlying login modules. Login modules use the CallbackHandler both to gather input from users, such as a password or smart card PIN, and to supply information to users, such as status information. By allowing the application to specify the CallbackHandler, underlying LoginModules remain independent from the different ways applications interact with users. For example, a CallbackHandler's implementation for a GUI application might display a window to solicit user input. On the other hand, a callbackhandler's implementation for a non-GUI environment, such as an application server, might simply obtain credential information by using an application server API. The callbackhandler interface has one method to implement:

void handle(Callback[] callbacks)
    throws java.io.IOException, 
           UnsupportedCallbackException;

The Callback interface is the last authentication class we will look at. This is a tagging interface for which several default implementations are provided, including the NameCallback and PasswordCallback used in an earlier example. A LoginModule uses a Callback to request information required by the authentication mechanism. LoginModules pass an array of Callbacks directly to the CallbackHandler.handle method during the authentication's login phase. If a callbackhandler does not understand how to use a Callback object passed into the handle method, it throws an UnsupportedCallbackException to abort the login call.

8.3. The JBoss Security Model

Similar to the rest of the JBoss architecture, security at the lowest level is defined as a set of interfaces for which alternate implementations may be provided. Three basic interfaces define the JBoss server security layer: org.jboss.security.AuthenticationManager, org.jboss.security.RealmMapping, and org.jboss.security.SecurityProxy. Figure 8.8, “The key security model interfaces and their relationship to the JBoss server EJB container elements.” shows a class diagram of the security interfaces and their relationship to the EJB container architecture.

The key security model interfaces and their relationship to the JBoss server EJB container elements.

Figure 8.8. The key security model interfaces and their relationship to the JBoss server EJB container elements.

The light blue classes represent the security interfaces while the yellow classes represent the EJB container layer. The two interfaces required for the implementation of the J2EE security model are org.jboss.security.AuthenticationManager and org.jboss.security.RealmMapping. The roles of the security interfaces presented in Figure 8.8, “The key security model interfaces and their relationship to the JBoss server EJB container elements.” are summarized in the following list.

  • AuthenticationManager: This interface is responsible for validating credentials associated with principals. Principals are identities, such as usernames, employee numbers, and social security numbers. Credentials are proof of the identity, such as passwords, session keys, and digital signatures. The isValid method is invoked to determine whether a user identity and associated credentials as known in the operational environment are valid proof of the user's identity.

  • RealmMapping: This interface is responsible for principal mapping and role mapping. The getPrincipal method takes a user identity as known in the operational environment and returns the application domain identity. The doesUserHaveRole method validates that the user identity in the operation environment has been assigned the indicated role from the application domain.

  • SecurityProxy: This interface describes the requirements for a custom SecurityProxyInterceptor plugin. A SecurityProxy allows for the externalization of custom security checks on a per-method basis for both the EJB home and remote interface methods.

  • SubjectSecurityManager: This is a subinterface of AuthenticationManager that adds accessor methods for obtaining the security domain name of the security manager and the current thread's authenticated Subject.

  • SecurityDomain: This is an extension of the AuthenticationManager, RealmMapping, and SubjectSecurityManager interfaces. It is a move to a comprehensive security interface based on the JAAS Subject, a java.security.KeyStore, and the JSSE com.sun.net.ssl.KeyManagerFactory and com.sun.net.ssl.TrustManagerFactory interfaces. This interface is a work in progress that will be the basis of a multi-domain security architecture that will better support ASP style deployments of applications and resources.

Note that the AuthenticationManager, RealmMapping and SecurityProxy interfaces have no association to JAAS related classes. Although the JBossSX framework is heavily dependent on JAAS, the basic security interfaces required for implementation of the J2EE security model are not. The JBossSX framework is simply an implementation of the basic security plug-in interfaces that are based on JAAS. The component diagram presented in Figure 8.9, “The relationship between the JBossSX framework implementation classes and the JBoss server EJB container layer.” illustrates this fact. The implication of this plug-in architecture is that you are free to replace the JAAS-based JBossSX implementation classes with your own custom security manager implementation that does not make use of JAAS, if you so desire. You'll see how to do this when you look at the JBossSX MBeans available for the configuration of JBossSX in Figure 8.9, “The relationship between the JBossSX framework implementation classes and the JBoss server EJB container layer.”.

The relationship between the JBossSX framework implementation classes and the JBoss server EJB container layer.

Figure 8.9. The relationship between the JBossSX framework implementation classes and the JBoss server EJB container layer.

8.3.1. Enabling Declarative Security in JBoss Revisited

Earlier in this chapter, the discussion of the J2EE standard security model ended with a requirement for the use of JBoss server-specific deployment descriptor to enable security. The details of this configuration are presented here. Figure 8.10, “The security element subsets of the JBoss server jboss.xml and jboss-web.xml deployment descriptors.” shows the JBoss-specific EJB and web application deployment descriptor's security-related elements.

The security element subsets of the JBoss server jboss.xml and jboss-web.xml deployment descriptors.

Figure 8.10. The security element subsets of the JBoss server jboss.xml and jboss-web.xml deployment descriptors.

The value of a security-domain element specifies the JNDI name of the security manager interface implementation that JBoss uses for the EJB and web containers. This is an object that implements both of the AuthenticationManager and RealmMapping interfaces. When specified as a top-level element it defines what security domain in effect for all EJBs in the deployment unit. This is the typical usage because mixing security managers within a deployment unit complicates inter-component operation and administration.

To specify the security domain for an individual EJB, you specify the security-domain at the container configuration level. This will override any top-level security-domain element.

The unauthenticated-principal element specifies the name to use for the Principal object returned by the EJBContext.getUserPrincipal method when an unauthenticated user invokes an EJB. Note that this conveys no special permissions to an unauthenticated caller. Its primary purpose is to allow unsecured servlets and JSP pages to invoke unsecured EJBs and allow the target EJB to obtain a non-null Principal for the caller using the getUserPrincipal method. This is a J2EE specification requirement.

The security-proxy element identifies a custom security proxy implementation that allows per-request security checks outside the scope of the EJB declarative security model without embedding security logic into the EJB implementation. This may be an implementation of the org.jboss.security.SecurityProxy interface, or just an object that implements methods in the home, remote, local home or local interfaces of the EJB to secure without implementing any common interface. If the given class does not implement the SecurityProxy interface, the instance must be wrapped in a SecurityProxy implementation that delegates the method invocations to the object. The org.jboss.security.SubjectSecurityProxy is an example SecurityProxy implementation used by the default JBossSX installation.

Take a look at a simple example of a custom SecurityProxy in the context of a trivial stateless session bean. The custom SecurityProxy validates that no one invokes the bean's echo method with a four-letter word as its argument. This is a check that is not possible with role-based security; you cannot define a FourLetterEchoInvoker role because the security context is the method argument, not a property of the caller. The code for the custom SecurityProxy is given in Example 8.7, “The example 1 custom EchoSecurityProxy implementation that enforces the echo argument-based security constraint.”, and the full source code is available in the src/main/org/jboss/chap8/ex1 directory of the book examples.

Example 8.7. The example 1 custom EchoSecurityProxy implementation that enforces the echo argument-based security constraint.

package org.jboss.chap8.ex1;
                
import java.lang.reflect.Method;
import javax.ejb.EJBContext;
                
import org.apache.log4j.Category;
                
import org.jboss.security.SecurityProxy;
                
/** A simple example of a custom SecurityProxy implementation
 *  that demonstrates method argument based security checks.
 * @author Scott.Stark@jboss.org
 * @version $Revision: 1.16 $
 */
public class EchoSecurityProxy implements SecurityProxy
{
    Category log = Category.getInstance(EchoSecurityProxy.class);
    Method echo;
    
    public void init(Class beanHome, Class beanRemote,
                     Object securityMgr)
        throws InstantiationException
    {
        log.debug("init, beanHome="+beanHome
                  + ", beanRemote="+beanRemote
                  + ", securityMgr="+securityMgr);
        // Get the echo method for equality testing in invoke
        try {
            Class[] params = {String.class};
            echo = beanRemote.getDeclaredMethod("echo", params);
        } catch(Exception e) {
            String msg = "Failed to finde an echo(String) method";
            log.error(msg, e);
            throw new InstantiationException(msg);
        }
    }
    
    public void setEJBContext(EJBContext ctx)
    {
        log.debug("setEJBContext, ctx="+ctx);
    }
    
    public void invokeHome(Method m, Object[] args)
        throws SecurityException
    {
        // We don't validate access to home methods
    }

    public void invoke(Method m, Object[] args, Object bean)
        throws SecurityException
    {
        log.debug("invoke, m="+m);
        // Check for the echo method
        if (m.equals(echo)) {
            // Validate that the msg arg is not 4 letter word
            String arg = (String) args[0];
            if (arg == null || arg.length() == 4)
                throw new SecurityException("No 4 letter words");
        }
        // We are not responsible for doing the invoke
    }
}           
                

The EchoSecurityProxy checks that the method to be invoked on the bean instance corresponds to the echo(String) method loaded the init method. If there is a match, the method argument is obtained and its length compared against 4 or null. Either case results in a SecurityException being thrown. Certainly this is a contrived example, but only in its application. It is a common requirement that applications must perform security checks based on the value of method arguments. The point of the example is to demonstrate how custom security beyond the scope of the standard declarative security model can be introduced independent of the bean implementation. This allows the specification and coding of the security requirements to be delegated to security experts. Since the security proxy layer can be done independent of the bean implementation, security can be changed to match the deployment environment requirements.

The associated jboss.xml descriptor that installs the EchoSecurityProxy as the custom proxy for the EchoBean is given in Example 8.8, “The jboss.xml descriptor, which configures the EchoSecurityProxy as the custom security proxy for the EchoBean.”.

Example 8.8. The jboss.xml descriptor, which configures the EchoSecurityProxy as the custom security proxy for the EchoBean.

<jboss>
    <security-domain>java:/jaas/other</security-domain>
                
    <enterprise-beans>
        <session>
            <ejb-name>EchoBean</ejb-name>
            <security-proxy>org.jboss.chap8.ex1.EchoSecurityProxy</security-proxy>
        </session>
    </enterprise-beans>
</jboss> 

Now test the custom proxy by running a client that attempts to invoke the EchoBean.echo method with the arguments Hello and Four as illustrated in this fragment:

public class ExClient
{
    public static void main(String args[])
        throws Exception
    {
        Logger log = Logger.getLogger("ExClient");
        log.info("Looking up EchoBean");

        InitialContext iniCtx = new InitialContext();
        Object ref = iniCtx.lookup("EchoBean");
        EchoHome home = (EchoHome) ref;
        Echo echo = home.create();

        log.info("Created Echo");
        log.info("Echo.echo('Hello') = "+echo.echo("Hello"));
        log.info("Echo.echo('Four') = "+echo.echo("Four"));
    }
}  

The first call should succeed, while the second should fail due to the fact that Four is a four-letter word. Run the client as follows using Ant from the examples directory:

[examples]$ ant -Dchap=chap8 -Dex=1 run-example
run-example1:
     [copy] Copying 1 file to /tmp/jboss-4.0.1/server/default/deploy
     [echo] Waiting for 5 seconds for deploy...
     [java] [INFO,ExClient] Looking up EchoBean
     [java] [INFO,ExClient] Created Echo
     [java] [INFO,ExClient] Echo.echo('Hello') = Hello
     [java] Exception in thread "main" java.rmi.ServerException: RemoteException occurred in 
            server thread; nested exception is: 
     [java]     java.rmi.AccessException: SecurityException; nested exception is: 
     [java]     java.lang.SecurityException: No 4 letter words
...
     [java]     at org.jboss.chap8.ex1.ExClient.main(ExClient.java:25)
     [java] Caused by: java.rmi.AccessException: SecurityException; nested exception is: 
     [java]     java.lang.SecurityException: No 4 letter words
...

The result is that the echo('Hello') method call succeeds as expected and the echo('Four') method call results in a rather messy looking exception, which is also expected. The above output has been truncated to fit in the book. The key part to the exception is that the SecurityException("No 4 letter words") generated by the EchoSecurityProxy was thrown to abort the attempted method invocation as desired.

8.4. The JBoss Security Extension Architecture

The preceding discussion of the general JBoss security layer has stated that the JBossSX security extension framework is an implementation of the security layer interfaces. This is the primary purpose of the JBossSX framework. The details of the implementation are interesting in that it offers a great deal of customization for integration into existing security infrastructures. A security infrastructure can be anything from a database or LDAP server to a sophisticated security software suite. The integration flexibility is achieved using the pluggable authentication model available in the JAAS framework.

The heart of the JBossSX framework is org.jboss.security.plugins.JaasSecurityManager. This is the default implementation of the AuthenticationManager and RealmMapping interfaces. Figure 8.11, “The relationship between the security-domain component deployment descriptor value, the component container and the JaasSecurityManager.” shows how the JaasSecurityManager integrates into the EJB and web container layers based on the security-domain element of the corresponding component deployment descriptor.

The relationship between the security-domain component deployment descriptor value, the component container and the JaasSecurityManager.

Figure 8.11. The relationship between the security-domain component deployment descriptor value, the component container and the JaasSecurityManager.

Figure 8.11, “The relationship between the security-domain component deployment descriptor value, the component container and the JaasSecurityManager.” depicts an enterprise application that contains both EJBs and web content secured under the security domain jwdomain. The EJB and web containers have a request interceptor architecture that includes a security interceptor, which enforces the container security model. At deployment time, the security-domain element value in the jboss.xml and jboss-web.xml descriptors is used to obtain the security manager instance associated with the container. The security interceptor then uses the security manager to perform its role. When a secured component is requested, the security interceptor delegates security checks to the security manager instance associated with the container.

The JBossSX JaasSecurityManager implementation performs security checks based on the information associated with the Subject instance that results from executing the JAAS login modules configured under the name matching the security-domain element value. We will drill into the JaasSecurityManager implementation and its use of JAAS in the following section.

8.4.1. How the JaasSecurityManager Uses JAAS

The JaasSecurityManager uses the JAAS packages to implement the AuthenticationManager and RealmMapping interface behavior. In particular, its behavior derives from the execution of the login module instances that are configured under the name that matches the security domain to which the JaasSecurityManager has been assigned. The login modules implement the security domain's principal authentication and role-mapping behavior. Thus, you can use the JaasSecurityManager across different security domains simply by plugging in different login module configurations for the domains.

To illustrate the details of the JaasSecurityManager's usage of the JAAS authentication process, you will walk through a client invocation of an EJB home method invocation. The prerequisite setting is that the EJB has been deployed in the JBoss server and its home interface methods have been secured using method-permission elements in the ejb-jar.xml descriptor, and it has been assigned a security domain named jwdomain using the jboss.xml descriptor security-domain element.

An illustration of the steps involved in the authentication and authorization of a secured EJB home method invocation.

Figure 8.12. An illustration of the steps involved in the authentication and authorization of a secured EJB home method invocation.

Figure 8.12, “An illustration of the steps involved in the authentication and authorization of a secured EJB home method invocation.” provides a view of the client to server communication we will discuss. The numbered steps shown are:

  1. The client first has to perform a JAAS login to establish the principal and credentials for authentication, and this is labeled Client Side Login in the figure. This is how clients establish their login identities in JBoss. Support for presenting the login information via JNDI InitialContext properties is provided via an alternate configuration. A JAAS login entails creating a LoginContext instance and passing the name of the configuration to use. The configuration name is other. This one-time login associates the login principal and credentials with all subsequent EJB method invocations. Note that the process might not authenticate the user. The nature of the client-side login depends on the login module configuration that the client uses. In this example, the other client-side login configuration entry is set up to use the ClientLoginModule module (an org.jboss.security.ClientLoginModule). This is the default client side module that simply binds the username and password to the JBoss EJB invocation layer for later authentication on the server. The identity of the client is not authenticated on the client.

  2. Later, the client obtains the EJB home interface and attempts to create a bean. This event is labeled as Home Method Invocation. This results in a home interface method invocation being sent to the JBoss server. The invocation includes the method arguments passed by the client along with the user identity and credentials from the client-side JAAS login performed in step 1.

  3. On the server side, the security interceptor first requires authentication of the user invoking the call, which, as on the client side, involves a JAAS login.

  4. The security domain under which the EJB is secured determines the choice of login modules. The security domain name is used as the login configuration entry name passed to the LoginContext constructor. The EJB security domain is jwdomain. If the JAAS login authenticates the user, a JAAS Subject is created that contains the following in its PrincipalsSet:

    • A java.security.Principal that corresponds to the client identity as known in the deployment security environment.

    • A java.security.acl.Group named Roles that contains the role names from the application domain to which the user has been assigned. org.jboss.security.SimplePrincipal objects are used to represent the role names; SimplePrincipal is a simple string-based implementation of Principal. These roles are used to validate the roles assigned to methods in ejb-jar.xml and the EJBContext.isCallerInRole(String) method implementation.

    • An optional java.security.acl.Group named CallerPrincipal, which contains a single org.jboss.security.SimplePrincipal that corresponds to the identity of the application domain's caller. The CallerPrincipal sole group member will be the value returned by the EJBContext.getCallerPrincipal() method. The purpose of this mapping is to allow a Principal as known in the operational security environment to map to a Principal with a name known to the application. In the absence of a CallerPrincipal mapping the deployment security environment principal is used as the getCallerPrincipal method value. That is, the operational principal is the same as the application domain principal.

  5. The final step of the security interceptor check is to verify that the authenticated user has permission to invoke the requested method This is labeled as Server Side Authorization in Figure 8.12, “An illustration of the steps involved in the authentication and authorization of a secured EJB home method invocation.”. Performing the authorization this entails the following steps:

    • Obtain the names of the roles allowed to access the EJB method from the EJB container. The role names are determined by ejb-jar.xml descriptor role-name elements of all method-permission elements containing the invoked method.

    • If no roles have been assigned, or the method is specified in an exclude-list element, then access to the method is denied. Otherwise, the doesUserHaveRole method is invoked on the security manager by the security interceptor to see if the caller has one of the assigned role names. This method iterates through the role names and checks if the authenticated user's Subject Roles group contains a SimplePrincipal with the assigned role name. Access is allowed if any role name is a member of the Roles group. Access is denied if none of the role names are members.

    • If the EJB was configured with a custom security proxy, the method invocation is delegated to it. If the security proxy wants to deny access to the caller, it will throw a java.lang.SecurityException. If no SecurityException is thrown, access to the EJB method is allowed and the method invocation passes to the next container interceptor. Note that the SecurityProxyInterceptor handles this check and this interceptor is not shown.

Every secured EJB method invocation, or secured web content access, requires the authentication and authorization of the caller because security information is handled as a stateless attribute of the request that must be presented and validated on each request. This can be an expensive operation if the JAAS login involves client-to-server communication. Because of this, the JaasSecurityManager supports the notion of an authentication cache that is used to store principal and credential information from previous successful logins. You can specify the authentication cache instance to use as part of the JaasSecurityManager configuration as you will see when the associated MBean service is discussed in following section. In the absence of any user-defined cache, a default cache that maintains credential information for a configurable period of time is used.

8.4.2. The JaasSecurityManagerService MBean

The JaasSecurityManagerService MBean service manages security managers. Although its name begins with Jaas, the security managers it handles need not use JAAS in their implementation. The name arose from the fact that the default security manager implementation is the JaasSecurityManager. The primary role of the JaasSecurityManagerService is to externalize the security manager implementation. You can change the security manager implementation by providing an alternate implementation of the AuthenticationManager and RealmMapping interfaces.

The second fundamental role of the JaasSecurityManagerService is to provide a JNDI javax.naming.spi.ObjectFactory implementation to allow for simple code-free management of the JNDI name to security manager implementation mapping. It has been mentioned that security is enabled by specifying the JNDI name of the security manager implementation via the security-domain deployment descriptor element. When you specify a JNDI name, there has to be an object-binding there to use. To simplify the setup of the JNDI name to security manager bindings, the JaasSecurityManagerService manages the association of security manager instances to names by binding a next naming system reference with itself as the JNDI ObjectFactory under the name java:/jaas. This allows one to use a naming convention of the form java:/jaas/XYZ as the value for the security-domain element, and the security manager instance for the XYZ security domain will be created as needed for you. The security manager for the domain XYZ is created on the first lookup against the java:/jaas/XYZ binding by creating an instance of the class specified by the SecurityManagerClassName attribute using a constructor that takes the name of the security domain. For example, consider the following container security configuration snippet:

<jboss>
    <!-- Configure all containers to be secured under the "hades" security domain -->
    <security-domain>java:/jaas/hades</security-domain>
    <!-- ... -->
</jboss> 

Any lookup of the name java:/jaas/hades will return a security manager instance that has been associated with the security domain named hades. This security manager will implement the AuthenticationManager and RealmMapping security interfaces and will be of the type specified by the JaasSecurityManagerService SecurityManagerClassName attribute.

The JaasSecurityManagerService MBean is configured by default for use in the standard JBoss distribution, and you can often use the default configuration as is. The configurable attributes of the JaasSecurityManagerService include:

  • SecurityManagerClassName: The name of the class that provides the security manager implementation. The implementation must support both the org.jboss.security.AuthenticationManager and org.jboss.security.RealmMapping interfaces. If not specified this defaults to the JAAS-based org.jboss.security.plugins.JaasSecurityManager.

  • CallbackHandlerClassName: The name of the class that provides the javax.security.auth.callback.CallbackHandler implementation used by the JaasSecurityManager. You can override the handler used by the JaasSecurityManager if the default implementation (org.jboss.security.auth.callback.SecurityAssociationHandler) does not meet your needs. This is a rather deep configuration that generally should not be set unless you know what you are doing.

  • SecurityProxyFactoryClassName: The name of the class that provides the org.jboss.security.SecurityProxyFactory implementation. If not specified this defaults to org.jboss.security.SubjectSecurityProxyFactory.

  • AuthenticationCacheJndiName: Specifies the location of the security credential cache policy. This is first treated as an ObjectFactory location capable of returning CachePolicy instances on a per-security-domain basis. This is done by appending the name of the security domain to this name when looking up the CachePolicy for a domain. If this fails, the location is treated as a single CachePolicy for all security domains. As a default, a timed cache policy is used.

  • DefaultCacheTimeout: Specifies the default timed cache policy timeout in seconds. The default value is 1800 seconds (30 minutes). The value you use for the timeout is a tradeoff between frequent authentication operations and how long credential information may be out of synch with respect to the security information store. If you want to disable caching of security credentials, set this to 0 to force authentication to occur every time. This has no affect if the AuthenticationCacheJndiName has been changed from the default value.

  • DefaultCacheResolution: Specifies the default timed cache policy resolution in seconds. This controls the interval at which the cache current timestamp is updated and should be less than the DefaultCacheTimeout in order for the timeout to be meaningful. The default resolution is 60 seconds(1 minute). This has no affect if the AuthenticationCacheJndiName has been changed from the default value.

  • DefaultUnauthenticatedPrincipal: Specifies the principal to use for unauthenticated users. This setting makes it possible to set default permissions for users who have not been authenticated.

The JaasSecurityManagerService also supports a number of useful operations. These include flushing any security domain authentication cache at runtime, getting the list of active users in a security domain authentication cache, and any of the security manager interface methods.

Flushing a security domain authentication cache can be used to drop all cached credentials when the underlying store has been updated and you want the store state to be used immediately. The MBean operation signature is: public void flushAuthenticationCache(String securityDomain).

This can be invoked programmatically using the following code snippet:

MBeanServer server = ...;
String jaasMgrName = "jboss.security:service=JaasSecurityManager";
ObjectName jaasMgr = new ObjectName(jaasMgrName);
Object[] params = {domainName};
String[] signature = {"java.lang.String"};
server.invoke(jaasMgr, "flushAuthenticationCache", params, signature);

Getting the list of active users provides a snapshot of the Principals keys in a security domain authentication cache that are not expired. The MBean operation signature is: public List getAuthenticationCachePrincipals(String securityDomain).

This can be invoked programmatically using the following code snippet:

MBeanServer server = ...;
String jaasMgrName = "jboss.security:service=JaasSecurityManager";
ObjectName jaasMgr = new ObjectName(jaasMgrName);
Object[] params = {domainName};
String[] signature = {"java.lang.String"};
List users = (List) server.invoke(jaasMgr, "getAuthenticationCachePrincipals", 
                                  params, signature);

The security manager has a few additional access methods.

public boolean isValid(String securityDomain, Principal principal, Object credential);
public Principal getPrincipal(String securityDomain, Principal principal);
public boolean doesUserHaveRole(String securityDomain, Principal principal, 
                                Object credential, Set roles);
public Set getUserRoles(String securityDomain, Principal principal, Object credential);

They provide access to the corresponding AuthenticationManager and RealmMapping interface method of the associated security domain named by the securityDomain argument.

8.4.3. The JaasSecurityDomain MBean

The org.jboss.security.plugins.JaasSecurityDomain is an extension of JaasSecurityManager that adds the notion of a KeyStore, a JSSE KeyManagerFactory and a TrustManagerFactory for supporting SSL and other cryptographic use cases. The additional configurable attributes of the JaasSecurityDomain include:

  • KeyStoreType: The type of the KeyStore implementation. This is the type argument passed to the java.security.KeyStore.getInstance(String type) factory method. The default is JKS.

  • KeyStoreURL: A URL to the location of the KeyStore database. This is used to obtain an InputStream to initialize the KeyStore. If the string is not a value URL, it is treated as a file.

  • KeyStorePass: The password associated with the KeyStore database contents. The KeyStorePass is also used in combination with the Salt and IterationCount attributes to create a PBE secret key used with the encode/decode operations. The KeyStorePass attribute value format is one of the following:

    • The plaintext password for the KeyStore The toCharArray() value of the string is used without any manipulation.

    • A command to execute to obtain the plaintext password. The format is {EXT}... where the ... is the exact command line that will be passed to the Runtime.exec(String) method to execute a platform-specific command. The first line of the command output is used as the password.

    • A class to create to obtain the plaintext password. The format is {CLASS}classname[:ctorarg] where the [:ctorarg] is an optional string that will be passed to the constructor when instantiating the classname. The password is obtained from classname by invoking a toCharArray() method if found, otherwise, the toString() method is used.

  • Salt: The PBEParameterSpec salt value.

  • IterationCount: The PBEParameterSpec iteration count value.

  • TrustStoreType: The type of the TrustStore implementation. This is the type argument passed to the java.security.KeyStore.getInstance(String type) factory method. The default is JKS.

  • TrustStoreURL: A URL to the location of the TrustStore database. This is used to obtain an InputStream to initialize the KeyStore. If the string is not a value URL, it is treated as a file.

  • TrustStorePass: The password associated with the trust store database contents. The TrustStorePass is a simple password and doesn't have the same configuration options as the KeyStorePass.

  • ManagerServiceName: Sets the JMX object name string of the security manager service MBean. This is used to register the defaults to register the JaasSecurityDomain as a the security manager under java:/jaas/<domain> where <domain> is the name passed to the MBean constructor. The name defaults to jboss.security:service=JaasSecurityManager.

8.5. Defining Security Domains

The standard way of configuring security domains for authentication and authorization in JBoss is to use the XML login configuration file. The login configuration policy defines a set of named security domains that each define a stack of login modules that will be called upon to authenticate and authorize users.

The XML configuration file conforms to the DTD given by Figure 8.13, “The XMLLoginConfig DTD”. This DTD can be found in docs/dtd/security_config.dtd.

The XMLLoginConfig DTD
The XMLLoginConfig DTD

Figure 8.13. The XMLLoginConfig DTD

The following example shows a simple configuration named jmx-console that is backed by a single login module. The login module is configured by a simple set of name/value configuration pairs that have meaning to the login module in question. We'll see what these options mean later, for now we'll just be concerned with the structure of the configuration file.

<application-policy name="jmx-console">
    <authentication>
        <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule" flag="required">
            <module-option name="usersProperties">props/jmx-console-users.properties</module-option>
            <module-option name="rolesProperties">props/jmx-console-roles.properties</module-option>
        </login-module>
    </authentication>
</application-policy>

The name attribute of the application-policy is the login configuration name. Applications policy elements will be bound by that name in JNDI under the the java:/jaas context. Applications will link to security domains through this JNDI name in their deployment descriptors. (See the security-domain elements in jboss.xml, jboss-web.xml and jboss-service.xml files for examples)

The code attribute of the login-module element specifies the class name of the login module implementation. The required flag attribute controls the overall behavior of the authentication stack. The allowed values and meanings are:

  • required: The login module is required to succeed for the authentication to be successful. If any required module fails, the authentication will fail. The remaining login modules in the stack will be called regardless of the outcome of the authentication.

  • requisite: The login module is required to succeed. If it succeeds, authentication continues down the login stack. If it fails, control immediately returns to the application.

  • sufficient: The login module is not required to succeed. If it does succeed, control immediately returns to the application. If it fails, authentication continues down the login stack.

  • optional: The login module is not required to succeed. Authentication still continues to proceed down the login stack regardless of whether the login module succeeds or fails.

The following example shows the definition of a security domain that uses multiple login modules. Since both modules are marked as sufficient, only one of them need to succeed for login to proceed.

<application-policy name="todo">
    <authentication>
        <login-module code="org.jboss.security.auth.spi.LdapLoginModule" 
                      flag="sufficient">
            <!-- LDAP configuration -->
        </login-module>
        <login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule" 
                      flag="sufficient">
            <!-- database configuration -->
        </login-module>
    </authentication>
</application-policy>

Each login module has its own set of configuration options. These are set as name/value pairs using the module-option elements. We'll cover module options in more depth when we look at the individual login modules available in JBoss AS.

8.5.1. Loading Security Domains

Authentication security domains are configured statically in the conf/login-config.xml file. The XMLLoginConfig MBean is resp onsible for loading security configurations from this configurations from a local configuration file. The MBean is defined as shown below.

<mbean code="org.jboss.security.auth.login.XMLLoginConfig"
       name="jboss.security:service=XMLLoginConfig">
    <attribute name="ConfigResource">login-config.xml</attribute>
</mbean>

The MBean supports the following attributes:

  • ConfigURL: specifies the URL of the XML login configuration file that should be loaded by this MBean on startup. This must be a valid URL string representation.

  • ConfigResource: specifies the resource name of the XML login configuration file that should be loaded by this MBean on startup. The name is treated as a classpath resource for which a URL is located using the thread context class loader.

  • ValidateDTD: a flag indicating if the XML configuration should be validated against its DTD. This defaults to true.

The MBean also supports the following operations that allow one to dynamically extend the login configurations at runtime. Note that any operation that attempts to alter login configuration requires a javax.security.auth.AuthPermission("refreshLoginConfiguration") when running with a security manager. The org.jboss.chap8.service.SecurityConfig service demonstrates how this can be used to add/remove a deployment specific security configuration dynamically.

  • void addAppConfig(String appName, AppConfigurationEntry[] entries): this adds the given login module configuration stack to the current configuration under the given appName. This replaces any existing entry under that name.

  • void removeAppConfig(String appName): this removes the login module configuration registered under the given appName.

  • String[] loadConfig(URL configURL) throws Exception: this loads one or more login configurations from a URL representing either an XML or legacy Sun login configuration file. Note that all login configurations must be added or none will be added. It returns the names of the login configurations that were added.

  • void removeConfigs(String[] appNames): this removes the login configurations specified appNames array.

  • String displayAppConfig(String appName): this operation displays a simple string format of the named configuration if it exists.

The SecurityConfig MBean is responsible for selecting the javax.security.auth.login.Configuration to be used. The default configuration simply references the XMLLoginConfig MBean.

  <mbean code="org.jboss.security.plugins.SecurityConfig" 
       name="jboss.security:service=SecurityConfig">
    <attribute name="LoginConfig">jboss.security:service=XMLLoginConfig</attribute>
                 </mbean>

There is one configurable attribute:

  • LoginConfig: Specifies the JMX ObjectName string of the MBean that provides the default JAAS login configuration. When the SecurityConfig is started, this MBean is queried for its javax.security.auth.login.Configuration by calling its getConfiguration(Configuration currentConfig) operation. If the LoginConfig attribute is not specified then the default Sun Configuration implementation described in the Configuration class JavaDocs is used.

In addition to allowing for a custom JAAS login configuration implementation, this service allows configurations to be chained together in a stack at runtime. This allows one to push a login configuration onto the stack and latter pop it. This is a feature used by the security unit tests to install custom login configurations into a default JBoss installation. Pushing a new configuration is done using:

public void pushLoginConfig(String objectName) throws
                JMException, MalformedObjectNameException;

The objectName parameters specifies an MBean similar to the LoginConfig attribute. The current login configuration may be removed using:

public void popLoginConfig() throws JMException;

8.5.2. The DynamicLoginConfig service

Security domains defined in the login-config.xml file are essentially static. They are read when JBoss starts up, but there is no easy way to add a new security domain or change the definition for an existing one. The DynamicLoginConfig service allows you to dynamically deploy security domains. This allows you to specify JAAS login configuration as part of a deployment (or just as a standalone service) rather than having to edit the static login-config.xml file.

The service supports the following attributes:

  • AuthConfig: The resource path to the JAAS login configuration file to use. This defaults to login-config.xml

  • LoginConfigService: the XMLLoginConfig service name to use for loading. This service must support a String loadConfig(URL) operation to load the configurations.

  • SecurityManagerService: The SecurityManagerService name used to flush the registered security domains. This service must support a flushAuthenticationCache(String) operation to flush the case for the argument security domain. Setting this triggers the flush of the authentication caches when the service is stopped.

Here is an example MBean definition using the DynamicLoginConfig service.

<server>
    <mbean code="org.jboss.security.auth.login.DynamicLoginConfig" name="...">
        <attribute name="AuthConfig">login-config.xml</attribute>

        <!-- The service which supports dynamic processing of login-config.xml
         configurations.
        -->
        <depends optional-attribute-name="LoginConfigService">
            jboss.security:service=XMLLoginConfig </depends>

        <!-- Optionally specify the security mgr service to use when
         this service is stopped to flush the auth caches of the domains
         registered by this service.
        -->
        <depends optional-attribute-name="SecurityManagerService">
            jboss.security:service=JaasSecurityManager </depends>
    </mbean>
</server>

This will load the specified AuthConfig resource using the specified LoginConfigService MBean by invoking loadConfig with the appropriate resource URL. When the service is stopped the configurations are removed. The resource specified may be either an XML file, or a Sun JAAS login configuration.

8.5.3. Using JBoss Login Modules

JBoss includes several bundled login modules suitable for most user management needs. JBoss can read user information from a relational database, an LDAP server or flat files. In addition to these core login modules, JBoss provides several other login modules that provide user information for very customized needs in JBoss. Before we explore the individual login modules, let's take a look at a few login module configuration options that are common to multiple modules.

8.5.3.1. Password Stacking

Multiple login modules can be chained together in a stack, with each login module providing both the authentication and authorization components. This works for many use cases, but sometimes authentication and authorization are split across multiple user management stores. A previous example showed how to combine LDAP and a relational database, allowing a user to be authenticated by either system. However, consider the case where users are managed in a central LDAP server but application-specific roles are stored in the application's relational database. The password-stacking module option captures this relationship.

  • password-stacking: When password-stacking option is set to useFirstPass, this module first looks for a shared username and password under the property names javax.security.auth.login.name and javax.security.auth.login.password respectively in the login module shared state map. If found these are used as the principal name and password. If not found the principal name and password are set by this login module and stored under the property names javax.security.auth.login.name and javax.security.auth.login.password respectively.

To use password stacking, each login module should set password-stacking to useFirstPass. If a previous module configured for password stacking has authenticated the user, all the other stacking modules will consider the user authenticated and only attempt to provide a set of roles for the authorization step.

The following listing shows how password stacking could be used:

<application-policy name="todo">
    <authentication>
        <login-module code="org.jboss.security.auth.spi.LdapLoginModule" 
                      flag="required">
            <!-- LDAP configuration -->
            <module-option name="password-stacking">useFirstPass</module-option>
        </login-module>
        <login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule" 
                      flag="required">
            <!-- database configuration -->                
            <module-option name="password-stacking">useFirstPass</module-option>
        </login-module>
    </authentication>
</application-policy>

When using password stacking, it is usually appropriate to set all modules to be required to make sure that all modules are considered and have chance to contribute roles to the authorization process.

8.5.3.2. Password Hashing

Most of the login modules need to compare a client-supplied password to a password stored in a user management system. These modules generally work with plain text passwords, but can also be configured to support hashed passwords to prevent plain text passwords from being stored on the server side.

  • hashAlgorithm: The name of the java.security.MessageDigest algorithm to use to hash the password. There is no default so this option must be specified to enable hashing. Typical values are MD5 and SHA.

  • hashEncoding: The string format for the hashed pass and must be either base64, hex or rfc2617. The default is base64.

  • hashCharset: The encoding used to convert the clear text password to a byte array. The platform default encoding is the default.

  • hashUserPassword: This indicates that the hashing algorithm should be applied to the password the user submits. The hashed user password will be compared against the value in the login module, which is expected to be a hash of the password. The default is true.

  • hashStorePassword: This indicates that the hashing algorithm should be applied to the password stored on the server side. This is used for digest authentication where the user submits a hash of the user password along with a request-specific tokens from the server to be comare. JBoss uses the hash algorithm (for digest, this would be rfc2617) to compute a server-side hash that should match the hashed value sent from the client.

The following is an login module configuration that assigns unauthenticated users the principal name nobody and contains based64-encoded, MD5 hashes of the passwords in a usersb64.properties file.

<policy>
    <application-policy name="testUsersRoles">
        <authentication>
            <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule"
                          flag="required">
                <module-option name="hashAlgorithm">MD5</module-option>
                <module-option name="hashEncoding">base64</module-option>          
            </login-module>
        </authentication>
    </application-policy>
</policy>

If you need to generate passwords in code, the org.jboss.security.Util class provides a static helper method that will hash a password using a given encoding.

String hashedPassword = Util.createPasswordHash("MD5",
                                                Util.BASE64_ENCODING,
                                                null,
                                                null,
                                                "password");   

OpenSSL provides an alternative way to quickly generate hashed passwords.

echo -n password | openssl dgst -md5 -binary | openssl base64

In both cases, the text password should hash to "X03MO1qnZdYdgyfeuILPmQ==". This is the value that would need to be stored in the user store.

8.5.3.3. Unauthenticated Identity

Not all requests come in authenticated. The unauthenticated identity is a login module configuration option that assigns a specific identity (guest, for example) to requests that are made with no associated authentication information. This can be used to allow unprotected servlets to invoke methods on EJBs that do not require a specific role. Such a principal has no associated roles and so can only access either unsecured EJBs or EJB methods that are associated with the unchecked permission constraint.

  • unauthenticatedIdentity: This defines the principal name that should be assigned to requests that contain no authentication information.

8.5.3.4. UsersRolesLoginModule

The UsersRolesLoginModule is a simple login module that supports multiple users and user roles loaded from Java properties files. The username-to-password mapping file is called users.properties and the username-to-roles mapping file is called roles.properties. The properties files are loaded during initialization using the initialize method thread context class loader. This means that these files can be placed into the J2EE deployment JAR, the JBoss configuration directory, or any directory on the JBoss server or system classpath. The primary purpose of this login module is to easily test the security settings of multiple users and roles using properties files deployed with the application.

The users.properties file uses a username=password format with each user entry on a separate line as show here:

username1=password1
username2=password2
...

The roles.properties file uses as username=role1,role2,... format with an optional group name value. For example:

username1=role1,role2,...
username1.RoleGroup1=role3,role4,...
username2=role1,role3,...

The username.XXX form of property name is used to assign the username roles to a particular named group of roles where the XXX portion of the property name is the group name. The username=... form is an abbreviation for username.Roles=..., where the Roles group name is the standard name the JaasSecurityManager expects to contain the roles which define the users permissions.

The following would be equivalent definitions for the jduke username:

jduke=TheDuke,AnimatedCharacter
jduke.Roles=TheDuke,AnimatedCharacter

The supported login module configuration options include the following:

  • usersProperties: The name of the properties resource containing the username to password mappings. This defaults to users.properties.

  • rolesProperties: The name of the properties resource containing the username to roles mappings. This defaults to roles.properties.

This login module supports password stacking, password hashing and unauthenticated identity.

8.5.3.5. LdapLoginModule

The LdapLoginModule is a LoginModule implementation that authenticates against an LDAP server. You would use the LdapLoginModule if your username and credentials are stored in an LDAP server that is accessible using a JNDI LDAP provider.

The LDAP connectivity information is provided as configuration options that are passed through to the environment object used to create JNDI initial context. The standard LDAP JNDI properties used include the following:

  • java.naming.factory.initial: The classname of the InitialContextFactory implementation. This defaults to the Sun LDAP provider implementation com.sun.jndi.ldap.LdapCtxFactory.

  • java.naming.provider.url: The LDAP URL for the LDAP server

  • java.naming.security.authentication: The security level to use. This defaults to simple.

  • java.naming.security.protocol: The transport protocol to use for secure access, such as, SSL.

  • java.naming.security.principal: The principal for authenticating the caller to the service. This is built from other properties as described below.

  • java.naming.security.credentials: The value of the property depends on the authentication scheme. For example, it could be a hashed password, clear-text password, key, certificate, and so on.

The supported login module configuration options include the following:

  • principalDNPrefix: A prefix to add to the username to form the user distinguished name. See principalDNSuffix for more info.

  • principalDNSuffix: A suffix to add to the username when forming the user distinguished name. This is useful if you prompt a user for a username and you don't want the user to have to enter the fully distinguished name. Using this property and principalDNSuffix the userDN will be formed as principalDNPrefix + username + principalDNSuffix

  • useObjectCredential: A true/false value that indicates that the credential should be obtained as an opaque Object using the org.jboss.security.auth.callback.ObjectCallback type of Callback rather than as a char[] password using a JAAS PasswordCallback. This allows for passing non-char[] credential information to the LDAP server.

  • rolesCtxDN: The fixed distinguished name to the context to search for user roles.

  • userRolesCtxDNAttributeName: The name of an attribute in the user object that contains the distinguished name to the context to search for user roles. This differs from rolesCtxDN in that the context to search for a user's roles can be unique for each user.

  • roleAttributeID: The name of the attribute that contains the user roles. If not specified this defaults to roles.

  • roleAttributeIsDN: A flag indicating whether the roleAttributeID contains the fully distinguished name of a role object, or the role name. If false, the role name is taken from the value of roleAttributeID. If true, the role attribute represents the distinguished name of a role object. The role name is taken from the value of the roleNameAttributeId attribute of the context name by the distinguished name. In certain directory schemas (e.g., MS ActiveDirectory), role attributes in the user object are stored as DNs to role objects instead of as simple names, in which case, this property should be set to true. The default is false.

  • roleNameAttributeID: The name of the attribute of the context pointed to by the roleCtxDN distinguished name value which contains the role name. If the roleAttributeIsDN property is set to true, this property is used to find the role object's name attribute. The default is group.

  • uidAttributeID: The name of the attribute in the object containing the user roles that corresponds to the userid. This is used to locate the user roles. If not specified this defaults to uid.

  • matchOnUserDN: A true/false flag indicating if the search for user roles should match on the user's fully distinguished name. If false, just the username is used as the match value against the uidAttributeName attribute. If true, the full userDN is used as the match value.

  • unauthenticatedIdentity: The principal name that should be assigned to requests that contain no authentication information. This behavior is inherited from the UsernamePasswordLoginModule superclass.

  • allowEmptyPasswords: A flag indicating if empty (length 0) passwords should be passed to the LDAP server. An empty password is treated as an anonymous login by some LDAP servers and this may not be a desirable feature. Set this to false to reject empty passwords or true to have the LDAP server validate the empty password. The default is true.

The authentication of a user is performed by connecting to the LDAP server based on the login module configuration options. Connecting to the LDAP server is done by creating an InitialLdapContext with an environment composed of the LDAP JNDI properties described previously in this section. The Context.SECURITY_PRINCIPAL is set to the distinguished name of the user as obtained by the callback handler in combination with the principalDNPrefix and principalDNSuffix option values, and the Context.SECURITY_CREDENTIALS property is either set to the String password or the Object credential depending on the useObjectCredential option.

Once authentication has succeeded by virtue of being able to create an InitialLdapContext instance, the user's roles are queried by performing a search on the rolesCtxDN location with search attributes set to the roleAttributeName and uidAttributeName option values. The roles names are obtaining by invoking the toString method on the role attributes in the search result set.

The following is a sample login-config.xml entry.

    <application-policy name="testLDAP">
        <authentication>
            <login-module code="org.jboss.security.auth.spi.LdapLoginModule"
                          flag="required">
                <module-option name="java.naming.factory.initial"> 
                    com.sun.jndi.ldap.LdapCtxFactory
                    </module-option>
                <module-option name="java.naming.provider.url">
                    ldap://ldaphost.jboss.org:1389/
                </module-option>
                <module-option name="java.naming.security.authentication">
                    simple
                </module-option>
                <module-option name="principalDNPrefix">uid=</module-option>                    
                <module-option name="principalDNSuffix">
                    ,ou=People,dc=jboss,dc=org
                </module-option>

                <module-option name="rolesCtxDN">
                    ou=Roles,dc=jboss,dc=org
                </module-option>
                <module-option name="uidAttributeID">member</module-option>
                <module-option name="matchOnUserDN">true</module-option>

                <module-option name="roleAttributeID">cn</module-option>
                <module-option name="roleAttributeIsDN">false </module-option>
            </login-module>
        </authentication>
    </application-policy>

An LDIF file representing the structure of the directory this data operates against is shown below.

dn: dc=jboss,dc=org
objectclass: top
objectclass: dcObject
objectclass: organization
dc: jboss
o: JBoss

dn: ou=People,dc=jboss,dc=org
objectclass: top
objectclass: organizationalUnit
ou: People

dn: uid=jduke,ou=People,dc=jboss,dc=org
objectclass: top
objectclass: uidObject
objectclass: person
uid: jduke
cn: Java Duke
sn: Duke
userPassword: theduke

dn: ou=Roles,dc=jboss,dc=org
objectclass: top
objectclass: organizationalUnit
ou: Roles

dn: cn=JBossAdmin,ou=Roles,dc=jboss,dc=org
objectclass: top
objectclass: groupOfNames
cn: JBossAdmin
member: uid=jduke,ou=People,dc=jboss,dc=org
description: the JBossAdmin group

Looking back at the testLDAP login module configuration, the java.naming.factory.initial, java.naming.factory.url and java.naming.security options indicate the Sun LDAP JNDI provider implementation will be used, the LDAP server is located on host ldaphost.jboss.org on port 1389, and that the LDAP simple authentication method will be use to connect to the LDAP server.

The login module attempts to connect to the LDAP server using a DN representing the user it is trying to authenticate. This DN is constructed from the principalDNPrefix, passed in, the username of the user and the principalDNSuffix as described above. In this example, the username jduke would map to uid=jduke,ou=People,dc=jboss,dc=org. We've assumed the LDAP server authenticates users using the userPassword attribute of the user's entry (theduke in this example). This is the way most LDAP servers work, however, if your LDAP server handles authentication differently you will need to set the authentication credentials in a way that makes sense for your server.

Once authentication succeeds, the roles on which authorization will be based are retrieved by performing a subtree search of the rolesCtxDN for entries whose uidAttributeID match the user. If matchOnUserDN is true the search will be based on the full DN of the user. Otherwise the search will be based on the actual user name entered. In this example, the search is under ou=Roles,dc=jboss,dc=org for any entries that have a member attribute equal to uid=jduke,ou=People,dc=jboss,dc=org. The search would locate cn=JBossAdmin under the roles entry.

The search returns the attribute specified in the roleAttributeID option. In this example, the attribute is cn. The value returned would be JBossAdmin, so the jduke user is assigned to the JBossAdmin role.

It's often the case that a local LDAP server provides identity and authentication services but is unable to use the authorization services. This is because application roles don't always map well onto LDAP groups, and LDAP administrators are often hesitant to allow external application-specific data in central LDAP servers. For this reason, the LDAP authentication module is often paired with another login module, such as the database login module, that can provide roles more suitable to the application being developed.

This login module also supports unauthenticated identity and password stacking.

8.5.3.6. DatabaseServerLoginModule

The DatabaseServerLoginModule is a JDBC based login module that supports authentication and role mapping. You would use this login module if you have your username, password and role information relational database. The DatabaseServerLoginModule is based on two logical tables:

Table Principals(PrincipalID text, Password text)
Table Roles(PrincipalID text, Role text, RoleGroup text)

The Principals table associates the user PrincipalID with the valid password and the Roles table associates the user PrincipalID with its role sets. The roles used for user permissions must be contained in rows with a RoleGroup column value of Roles. The tables are logical in that you can specify the SQL query that the login module uses. All that is required is that the java.sql.ResultSet has the same logical structure as the Principals and Roles tables described previously. The actual names of the tables and columns are not relevant as the results are accessed based on the column index. To clarify this notion, consider a database with two tables, Principals and Roles, as already declared. The following statements build the tables to contain a PrincipalID java with a Password of echoman in the Principals table, a PrincipalID java with a role named Echo in the Roles RoleGroup in the Roles table, and a PrincipalID java with a role named caller_java in the CallerPrincipal RoleGroup in the Roles table:

INSERT INTO Principals VALUES('java', 'echoman')
INSERT INTO Roles VALUES('java', 'Echo', 'Roles')
INSERT INTO Roles VALUES('java', 'caller_java', 'CallerPrincipal')

The supported login module configuration options include the following:

  • dsJndiName: The JNDI name for the DataSource of the database containing the logical Principals and Roles tables. If not specified this defaults to java:/DefaultDS.

  • principalsQuery: The prepared statement query equivalent to: select Password from Principals where PrincipalID=?. If not specified this is the exact prepared statement that will be used.

  • rolesQuery: The prepared statement query equivalent to: select Role, RoleGroup from Roles where PrincipalID=?. If not specified this is the exact prepared statement that will be used.

  • ignorePasswordCase: A boolean flag indicating if the password comparison should ignore case. This can be useful for hashed password encoding where the case of the hashed password is not significant.

  • principalClass: An option that specifies a Principal implementation class. This must support a constructor taking a string argument for the principal name.

As an example DatabaseServerLoginModule configuration, consider a custom table schema like the following:

CREATE TABLE Users(username VARCHAR(64) PRIMARY KEY, passwd VARCHAR(64))
CREATE TABLE UserRoles(username VARCHAR(64), userRoles VARCHAR(32))

A corresponding login-config.xml entry would be:

<policy>
    <application-policy name="testDB">
        <authentication>
            <login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule"
                             flag="required">
                <module-option name="dsJndiName">java:/MyDatabaseDS</module-option>
                <module-option name="principalsQuery">
                    select passwd from Users username where username=?</module-option>
                <module-option name="rolesQuery">
                    select userRoles, 'Roles' from UserRoles where username=?</module-option>
            </login-module>
        </authentication>
    </application-policy>
</policy>

This module supports password stacking, password hashing and unathenticated identity.

8.5.3.7. BaseCertLoginModule

This is a login module which authenticates users based on X509 certificates. A typical use case for this login module is CLIENT-CERT authentication in the web tier. This login module only performs authentication. You need to combine it with another login module capable of acquiring the authorization roles to completely define access to a secured web or EJB component. Two subclasses of this login module, CertRolesLoginModule and DatabaseCertLoginModule extend the behavior to obtain the authorization roles from either a properties file or database.

The BaseCertLoginModule needs a KeyStore to perform user validation. This is obtained through a org.jboss.security.SecurityDomain implementation. Typically, the SecurityDomain implementation is configured using the org.jboss.security.plugins.JaasSecurityDomain MBean as shown in this jboss-service.xml configuration fragment:

<mbean code="org.jboss.security.plugins.JaasSecurityDomain"
       name="jboss.ch8:service=SecurityDomain">
    <constructor>
        <arg type="java.lang.String" value="jmx-console"/>
    </constructor>
    <attribute name="KeyStoreURL">resource:localhost.keystore</attribute>
    <attribute name="KeyStorePass">unit-tests-server</attribute>
</mbean>

This creates a security domain with the name jmx-console whose SecurityDomain implementation is available via JNDI under the name java:/jaas/jmx-console following the JBossSX security domain naming pattern. To secure a web application such as the jmx-console.war using client certs and role based authorization, one would first modify the web.xml to declare the resources to be secured, along with the allowed roles and security domain to be used for authentication and authorization.

<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC
                  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
                  "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app> 
    ... 
    <security-constraint>
        <web-resource-collection>
            <web-resource-name>HtmlAdaptor</web-resource-name>
            <description>An example security config that only allows users with
                the role JBossAdmin to access the HTML JMX console web
                application </description>
            <url-pattern>/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
        </web-resource-collection>
        <auth-constraint>
            <role-name>JBossAdmin</role-name>
        </auth-constraint>
    </security-constraint>
    <login-config>
        <auth-method>CLIENT-CERT</auth-method>
        <realm-name>JBoss JMX Console</realm-name>
    </login-config>
    <security-role>
        <role-name>JBossAdmin</role-name>
    </security-role>
</web-app>

Next we, need to specify the JBoss security domain in jboss-web.xml:

<jboss-web>
    <security-domain>java:/jaas/jmx-console</security-domain>
</jboss-web>

Finally, you need to define the login module configuration for the jmx-console security domain you just specified. This is done in the conf/login-config.xml file.

<application-policy name="jmx-console">
    <authentication>
        <login-module code="org.jboss.security.auth.spi.BaseCertLoginModule" 
                      flag="required">
            <module-option name="password-stacking">useFirstPass</module-option>
            <module-option name="securityDomain">java:/jaas/jmx-console</module-option>
        </login-module>
        <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule" 
                      flag="required">
            <module-option name="password-stacking">useFirstPass</module-option>
            <module-option name="usersProperties">jmx-console-users.properties</module-option>
            <module-option name="rolesProperties">jmx-console-roles.properties</module-option>
        </login-module>
    </authentication>
</application-policy>

Here the BaseCertLoginModule is used for authentication of the client cert, and the UsersRolesLoginModule is only used for authorization due to the password-stacking=useFirstPass option. Both the localhost.keystore and the jmx-console-roles.properties need an entry that maps to the principal associated with the client cert. By default, the principal is created using the client certificate distinguished name. Consider the following certificate:

[starksm@banshee9100 conf]$ keytool -printcert -file unit-tests-client.export
Owner: CN=unit-tests-client, OU=JBoss Inc., O=JBoss Inc., ST=Washington, C=US
Issuer: CN=jboss.com, C=US, ST=Washington, L=Snoqualmie Pass, EMAILADDRESS=admin
@jboss.com, OU=QA, O=JBoss Inc.
Serial number: 100103
Valid from: Wed May 26 07:34:34 PDT 2004 until: Thu May 26 07:34:34 PDT 2005
Certificate fingerprints:
         MD5:  4A:9C:2B:CD:1B:50:AA:85:DD:89:F6:1D:F5:AF:9E:AB
         SHA1: DE:DE:86:59:05:6C:00:E8:CC:C0:16:D3:C2:68:BF:95:B8:83:E9:58

The localhost.keystore would need this cert stored with an alias of CN=unit-tests-client, OU=JBoss Inc., O=JBoss Inc., ST=Washington, C=US and the jmx-console-roles.properties would also need an entry for the same entry. Since the DN contains many characters that are normally treated as delimiters, you will need to escape the problem characters using a backslash ('\') as shown here:

# A sample roles.properties file for use with the UsersRolesLoginModule
CN\=unit-tests-client,\ OU\=JBoss\ Inc.,\ O\=JBoss\ Inc.,\ ST\=Washington,\ C\=US=JBossAdmin
admin=JBossAdmin

8.5.3.8. IdentityLoginModule

The IdentityLoginModule is a simple login module that associates a hard-coded user name a to any subject authenticated against the module. It creates a SimplePrincipal instance using the name specified by the principal option. This login module is useful when you need to provide a fixed identity to a service and in development environments when you want to test the security associated with a given principal and associated roles.

The supported login module configuration options include:

  • principal: This is the name to use for the SimplePrincipal all users are authenticated as. The principal name defaults to guest if no principal option is specified.

  • roles: This is a comma-delimited list of roles that will be assigned to the user.

A sample XMLLoginConfig configuration entry that would authenticate all users as the principal named jduke and assign role names of TheDuke, and AnimatedCharacter is:

<policy>
    <application-policy name="testIdentity">
        <authentication>
            <login-module code="org.jboss.security.auth.spi.IdentityLoginModule"
                         flag="required">
                <module-option name="principal">jduke</module-option>
                <module-option name="roles">TheDuke,AnimatedCharater</module-option>
            </login-module>
        </authentication>
    </application-policy>
</policy> 

This module supports password stacking.

8.5.3.9. RunAsLoginModule

JBoss has a helper login module called RunAsLoginModule that pushes a run as role for the duration of the login phase of authentication, and pops the run as role in either the commit or abort phase. The purpose of this login module is to provide a role for other login modules that need to access secured resources in order to perform their authentication. An example would be a login module that accesses an secured EJB. This login module must be configured ahead of the login module(s) that need a run as role established.

The only login module configuration option is:

  • roleName: the name of the role to use as the run as role during login phase. If not specified a default of nobody is used.

8.5.3.10. ClientLoginModule

The ClientLoginModule is an implementation of LoginModule for use by JBoss clients for the establishment of the caller identity and credentials. This simply sets the org.jboss.security.SecurityAssociation.principal to the value of the NameCallback filled in by the callbackhandler, and the org.jboss.security.SecurityAssociation.credential to the value of the PasswordCallback filled in by the callbackhandler. This is the only supported mechanism for a client to establish the current thread's caller. Both stand-alone client applications and server environments, acting as JBoss EJB clients where the security environment has not been configured to use JBossSX transparently, need to use the ClientLoginModule. Of course, you could always set the org.jboss.security.SecurityAssociation information directly, but this is considered an internal API that is subject to change without notice.

Note that this login module does not perform any authentication. It merely copies the login information provided to it into the JBoss server EJB invocation layer for subsequent authentication on the server. If you need to perform client-side authentication of users you would need to configure another login module in addition to the ClientLoginModule.

The supported login module configuration options include the following:

  • multi-threaded: When the multi-threaded option is set to true, each login thread has its own principal and credential storage. This is useful in client environments where multiple user identities are active in separate threads. When true, each separate thread must perform its own login. When set to false the login identity and credentials are global variables that apply to all threads in the VM. The default for this option is false.

  • password-stacking: When password-stacking option is set to useFirstPass, this module first looks for a shared username and password using javax.security.auth.login.name and javax.security.auth.login.password respectively in the login module shared state map. This allows a module configured prior to this one to establish a valid username and password that should be passed to JBoss. You would use this option if you want to perform client-side authentication of clients using some other login module such as the LdapLoginModule.

  • restore-login-identity: When restore-login-identity is true, the SecurityAssociation principal and credential seen on entry to the login() method are saved and restored on either abort or logout. When false (the default), the abort and logout simply clear the SecurityAssociation. A restore-login-identity of true is needed if one need to change identities and then restore the original caller identity.

A sample login configuration for ClientLoginModule is the default configuration entry found in the JBoss distribution client/auth.conf file. The configuration is:

other {
    // Put your login modules that work without jBoss here
                
    // jBoss LoginModule
    org.jboss.security.ClientLoginModule required;
               
    // Put your login modules that need jBoss here
};  

8.5.4. Writing Custom Login Modules

If the login modules bundled with the JBossSX framework do not work with your security environment, you can write your own custom login module implementation that does. Recall from the section on the JaasSecurityManager architecture that the JaasSecurityManager expected a particular usage pattern of the Subject principals set. You need to understand the JAAS Subject class's information storage features and the expected usage of these features to be able to write a login module that works with the JaasSecurityManager. This section examines this requirement and introduces two abstract base LoginModule implementations that can help you implement your own custom login modules.

You can obtain security information associated with a Subject in six ways in JBoss using the following methods:

java.util.Set getPrincipals()
java.util.Set getPrincipals(java.lang.Class c)
java.util.Set getPrivateCredentials()
java.util.Set getPrivateCredentials(java.lang.Class c)
java.util.Set getPublicCredentials()
java.util.Set getPublicCredentials(java.lang.Class c)

For Subject identities and roles, JBossSX has selected the most natural choice: the principals sets obtained via getPrincipals() and getPrincipals(java.lang.Class). The usage pattern is as follows:

  • User identities (username, social security number, employee ID, and so on) are stored as java.security.Principal objects in the Subject Principals set. The Principal implementation that represents the user identity must base comparisons and equality on the name of the principal. A suitable implementation is available as the org.jboss.security.SimplePrincipal class. Other Principal instances may be added to the Subject Principals set as needed.

  • The assigned user roles are also stored in the Principals set, but they are grouped in named role sets using java.security.acl.Group instances. The Group interface defines a collection of Principals and/or Groups, and is a subinterface of java.security.Principal. Any number of role sets can be assigned to a Subject. Currently, the JBossSX framework uses two well-known role sets with the names Roles and CallerPrincipal. The Roles Group is the collection of Principals for the named roles as known in the application domain under which the Subject has been authenticated. This role set is used by methods like the EJBContext.isCallerInRole(String), which EJBs can use to see if the current caller belongs to the named application domain role. The security interceptor logic that performs method permission checks also uses this role set. The CallerPrincipal Group consists of the single Principal identity assigned to the user in the application domain. The EJBContext.getCallerPrincipal() method uses the CallerPrincipal to allow the application domain to map from the operation environment identity to a user identity suitable for the application. If a Subject does not have a CallerPrincipal Group, the application identity is the same as operational environment identity.

8.5.4.1. Support for the Subject Usage Pattern

To simplify correct implementation of the Subject usage patterns described in the preceding section, JBossSX includes two abstract login modules that handle the population of the authenticated Subject with a template pattern that enforces correct Subject usage. The most generic of the two is the org.jboss.security.auth.spi.AbstractServerLoginModule class. It provides a concrete implementation of the javax.security.auth.spi.LoginModule interface and offers abstract methods for the key tasks specific to an operation environment security infrastructure. The key details of the class are highlighted in the following class fragment. The JavaDoc comments detail the responsibilities of subclasses.

package org.jboss.security.auth.spi;
/**
 *  This class implements the common functionality required for a JAAS
 *  server-side LoginModule and implements the JBossSX standard
 *  Subject usage pattern of storing identities and roles. Subclass
 *  this module to create your own custom LoginModule and override the
 *  login(), getRoleSets(), and getIdentity() methods.
 */
public abstract class AbstractServerLoginModule
    implements javax.security.auth.spi.LoginModule
{
    protected Subject subject;
    protected CallbackHandler callbackHandler;
    protected Map sharedState;
    protected Map options;
    protected Logger log;

    /** Flag indicating if the shared credential should be used */
    protected boolean useFirstPass;
    /** 
     * Flag indicating if the login phase succeeded. Subclasses that
     * override the login method must set this to true on successful
     * completion of login
     */
    protected boolean loginOk;
                
    // ...
    /**
     * Initialize the login module. This stores the subject,
     * callbackHandler and sharedState and options for the login
     * session. Subclasses should override if they need to process
     * their own options. A call to super.initialize(...)  must be
     * made in the case of an override.
     *
     * <p>
     * The options are checked for the  <em>password-stacking</em> parameter.
     * If this is set to "useFirstPass", the login identity will be taken from the
     * <code>javax.security.auth.login.name</code> value of the sharedState map,
     * and the proof of identity from the
     * <code>javax.security.auth.login.password</code> value of the sharedState map.
     *
     * @param subject the Subject to update after a successful login.
     * @param callbackHandler the CallbackHandler that will be used to obtain the
     * the user identity and credentials.
     * @param sharedState a Map shared between all configured login module instances
     * @param options the parameters passed to the login module.
     */
    public void initialize(Subject subject,
                           CallbackHandler callbackHandler,
                           Map sharedState,
                           Map options)
    {
        // ...
    }
    

    /**
     *  Looks for javax.security.auth.login.name and
     *  javax.security.auth.login.password values in the sharedState
     *  map if the useFirstPass option was true and returns true if
     *  they exist. If they do not or are null this method returns
     *  false.  
     *  Note that subclasses that override the login method
     *  must set the loginOk var to true if the login succeeds in
     *  order for the commit phase to populate the Subject. This
     *  implementation sets loginOk to true if the login() method
     *  returns true, otherwise, it sets loginOk to false.
     */
    public boolean login() 
        throws LoginException
    {
        // ...
    }
    
    /**
     *  Overridden by subclasses to return the Principal that
     *  corresponds to the user primary identity.
     */
    abstract protected Principal getIdentity();
                
    /**
     *  Overridden by subclasses to return the Groups that correspond
     *  to the role sets assigned to the user. Subclasses should
     *  create at least a Group named "Roles" that contains the roles
     *  assigned to the user.  A second common group is
     *  "CallerPrincipal," which provides the application identity of
     *  the user rather than the security domain identity.
     * 
     *  @return Group[] containing the sets of roles
     */
    abstract protected Group[] getRoleSets() throws LoginException;
}

You'll need to pay attention to the loginOk instance variable. This must be set to true if the login succeeds, false otherwise by any subclasses that override the login method. Failure to set this variable correctly will result in the commit method either not updating the subject when it should, or updating the subject when it should not. Tracking the outcome of the login phase was added to allow login modules to be chained together with control flags that do not require that the login module succeed in order for the overall login to succeed.

The second abstract base login module suitable for custom login modules is the org.jboss.security.auth.spi.UsernamePasswordLoginModule. This login module further simplifies custom login module implementation by enforcing a string-based username as the user identity and a char[] password as the authentication credentials. It also supports the mapping of anonymous users (indicated by a null username and password) to a principal with no roles. The key details of the class are highlighted in the following class fragment. The JavaDoc comments detail the responsibilities of subclasses.

package org.jboss.security.auth.spi;

/**
 *  An abstract subclass of AbstractServerLoginModule that imposes a
 *  an identity == String username, credentials == String password
 *  view on the login process. Subclasses override the
 *  getUsersPassword() and getUsersRoles() methods to return the
 *  expected password and roles for the user.
 */
public abstract class UsernamePasswordLoginModule
    extends AbstractServerLoginModule
{
    /** The login identity */
    private Principal identity;
    /** The proof of login identity */
    private char[] credential;
    /** The principal to use when a null username and password are seen */
    private Principal unauthenticatedIdentity;

    /**
     * The message digest algorithm used to hash passwords. If null then
     * plain passwords will be used. */
    private String hashAlgorithm = null;

    /**
     *  The name of the charset/encoding to use when converting the
     * password String to a byte array. Default is the platform's
     * default encoding.
     */
     private String hashCharset = null;

    /** The string encoding format to use. Defaults to base64. */
    private String hashEncoding = null;
                
    // ...
                
    /** 
     *  Override the superclass method to look for an
     *  unauthenticatedIdentity property. This method first invokes
     *  the super version.
     *
     *  @param options,
     *  @option unauthenticatedIdentity: the name of the principal to
     *  assign and authenticate when a null username and password are
     *  seen.
     */
    public void initialize(Subject subject,
                           CallbackHandler callbackHandler,
                           Map sharedState,
                           Map options)
    {
        super.initialize(subject, callbackHandler, sharedState,
                         options);
        // Check for unauthenticatedIdentity option.
        Object option = options.get("unauthenticatedIdentity");
        String name = (String) option;
        if (name != null) {
            unauthenticatedIdentity = new SimplePrincipal(name);
        }
    }
                
    // ...
                
    /**
     *  A hook that allows subclasses to change the validation of the
     *  input password against the expected password. This version
     *  checks that neither inputPassword or expectedPassword are null
     *  and that inputPassword.equals(expectedPassword) is true;
     *
     *  @return true if the inputPassword is valid, false otherwise.
     */
    protected boolean validatePassword(String inputPassword,
                                       String expectedPassword)
    {
        if (inputPassword == null || expectedPassword == null) {
            return false;
        }
        return inputPassword.equals(expectedPassword);
    }
    
    /**
     *  Get the expected password for the current username available
     * via the getUsername() method. This is called from within the
     * login() method after the CallbackHandler has returned the
     * username and candidate password.
     *
     * @return the valid password String
     */
    abstract protected String getUsersPassword()
        throws LoginException;
}

The choice of subclassing the AbstractServerLoginModule versus UsernamePasswordLoginModule is simply based on whether a string-based username and credentials are usable for the authentication technology you are writing the login module for. If the string-based semantic is valid, then subclass UsernamePasswordLoginModule, otherwise subclass AbstractServerLoginModule.

The steps you are required to perform when writing a custom login module are summarized in the following depending on which base login module class you choose. When writing a custom login module that integrates with your security infrastructure, you should start by subclassing AbstractServerLoginModule or UsernamePasswordLoginModule to ensure that your login module provides the authenticated Principal information in the form expected by the JBossSX security manager.

When subclassing the AbstractServerLoginModule, you need to override the following:

  • void initialize(Subject, CallbackHandler, Map, Map): if you have custom options to parse.

  • boolean login(): to perform the authentication activity. Be sure to set the loginOk instance variable to true if login succeeds, false if it fails.

  • Principal getIdentity(): to return the Principal object for the user authenticated by the log() step.

  • Group[] getRoleSets(): to return at least one Group named Roles that contains the roles assigned to the Principal authenticated during login(). A second common Group is named CallerPrincipal and provides the user's application identity rather than the security domain identity.

When subclassing the UsernamePasswordLoginModule, you need to override the following:

  • void initialize(Subject, CallbackHandler, Map, Map): if you have custom options to parse.

  • Group[] getRoleSets(): to return at least one Group named Roles that contains the roles assigned to the Principal authenticated during login(). A second common Group is named CallerPrincipal and provides the user's application identity rather than the security domain identity.

  • String getUsersPassword(): to return the expected password for the current username available via the getUsername() method. The getUsersPassword() method is called from within login() after the callbackhandler returns the username and candidate password.

8.5.4.2. A Custom LoginModule Example

In this section we will develop a custom login module example. It will extend the UsernamePasswordLoginModule and obtains a user's password and role names from a JNDI lookup. The idea is that there is a JNDI context that will return a user's password if you perform a lookup on the context using a name of the form password/<username> where <username> is the current user being authenticated. Similarly, a lookup of the form roles/<username> returns the requested user's roles.

The source code for the example is located in the src/main/org/jboss/chap8/ex2 directory of the book examples. Example 8.9, “ A JndiUserAndPass custom login module” shows the source code for the JndiUserAndPass custom login module. Note that because this extends the JBoss UsernamePasswordLoginModule, all the JndiUserAndPass does is obtain the user's password and roles from the JNDI store. The JndiUserAndPass does not concern itself with the JAAS LoginModule operations.

Example 8.9.  A JndiUserAndPass custom login module

package org.jboss.chap8.ex2;
                    
import java.security.acl.Group;
import java.util.Map;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;

import org.jboss.security.SimpleGroup;
import org.jboss.security.SimplePrincipal;
import org.jboss.security.auth.spi.UsernamePasswordLoginModule;

/** 
 *  An example custom login module that obtains passwords and roles
 *  for a user from a JNDI lookup.
 *     
 *  @author Scott.Stark@jboss.org
 *  @version $Revision: 1.16 $
*/
public class JndiUserAndPass 
    extends UsernamePasswordLoginModule
{
    /** The JNDI name to the context that handles the password/username lookup */
    private String userPathPrefix;
    /** The JNDI name to the context that handles the roles/ username lookup */
    private String rolesPathPrefix;
    
    /**
     * Override to obtain the userPathPrefix and rolesPathPrefix options.
     */
    public void initialize(Subject subject, CallbackHandler callbackHandler,
                           Map sharedState, Map options)
    {
        super.initialize(subject, callbackHandler, sharedState, options);
        userPathPrefix = (String) options.get("userPathPrefix");
        rolesPathPrefix = (String) options.get("rolesPathPrefix");
    }
    
    /**
     *  Get the roles the current user belongs to by querying the
     * rolesPathPrefix + '/' + super.getUsername() JNDI location.
     */
    protected Group[] getRoleSets() throws LoginException
    {
        try {
            InitialContext ctx = new InitialContext();
            String rolesPath = rolesPathPrefix + '/' + super.getUsername();

            String[] roles = (String[]) ctx.lookup(rolesPath);
            Group[] groups = {new SimpleGroup("Roles")};
            log.info("Getting roles for user="+super.getUsername());
            for(int r = 0; r < roles.length; r ++) {
                SimplePrincipal role = new SimplePrincipal(roles[r]);
                log.info("Found role="+roles[r]);
                groups[0].addMember(role);
            }
            return groups;
        } catch(NamingException e) {
            log.error("Failed to obtain groups for
                        user="+super.getUsername(), e);
            throw new LoginException(e.toString(true));
        }
    }
                    
    /** 
     * Get the password of the current user by querying the
     * userPathPrefix + '/' + super.getUsername() JNDI location.
     */
    protected String getUsersPassword() 
        throws LoginException
    {
        try {
            InitialContext ctx = new InitialContext();
            String userPath = userPathPrefix + '/' + super.getUsername();
            log.info("Getting password for user="+super.getUsername());
            String passwd = (String) ctx.lookup(userPath);
            log.info("Found password="+passwd);
            return passwd;
        } catch(NamingException e) {
            log.error("Failed to obtain password for
                        user="+super.getUsername(), e);
            throw new LoginException(e.toString(true));
        }
    }   
}

The details of the JNDI store are found in the org.jboss.chap8.ex2.service.JndiStore MBean. This service binds an ObjectFactory that returns a javax.naming.Context proxy into JNDI. The proxy handles lookup operations done against it by checking the prefix of the lookup name against password and roles. When the name begins with password, a user's password is being requested. When the name begins with roles the user's roles are being requested. The example implementation always returns a password of theduke and an array of roles names equal to {"TheDuke", "Echo"} regardless of what the username is. You can experiment with other implementations as you wish.

The example code includes a simple session bean for testing the custom login module. To build, deploy and run the example, execute the following command in the examples directory.

[examples]$ ant -Dchap=chap8 -Dex=2 run-example
...
run-example2:
     [copy] Copying 1 file to /tmp/jboss-4.0.1/server/default/deploy
     [echo] Waiting for 5 seconds for deploy...
     [java] [INFO,ExClient] Login with username=jduke, password=theduke
     [java] [INFO,ExClient] Looking up EchoBean2
     [java] [INFO,ExClient] Created Echo
     [java] [INFO,ExClient] Echo.echo('Hello') = Hello
19:06:13,266 INFO  [EjbModule] Deploying EchoBean2
19:06:13,482 INFO  [JndiStore] Start, bound security/store
19:06:13,486 INFO  [SecurityConfig] Using JAAS AuthConfig: jar:file:/private/tmp/jboss-4.0.1/
server/default/tmp/deploy/tmp23012chap8-ex2.jar-contents/chap8-ex2.sar!/META-INF/login-config
.xml
19:06:13,654 INFO  [EJBDeployer] Deployed: file:/private/tmp/jboss-4.0.1/server/default/deplo
y/chap8-ex2.jar

The choice of using the JndiUserAndPass custom login module for the server side authentication of the user is determined by the login configuration for the example security domain. The EJB JAR META-INF/jboss.xml descriptor sets the security domain

<?xml version="1.0"?>
<jboss>
    <security-domain>java:/jaas/chap8-ex2</security-domain>
</jboss>

The SAR META-INF/login-config.xml descriptor defines the login module configuration.

<application-policy name = "chap8-ex2">
    <authentication>
        <login-module code="org.jboss.chap8.ex2.JndiUserAndPass"
                      flag="required">
            <module-option name = "userPathPrefix">/security/store/password</module-option>
            <module-option name = "rolesPathPrefix">/security/store/roles</module-option>
        </login-module>
    </authentication>
</application-policy>

8.6. The Secure Remote Password (SRP) Protocol

The SRP protocol is an implementation of a public key exchange handshake described in the Internet standards working group request for comments 2945(RFC2945). The RFC2945 abstract states:

This document describes a cryptographically strong network authentication mechanism known as the Secure Remote Password (SRP) protocol. This mechanism is suitable for negotiating secure connections using a user-supplied password, while eliminating the security problems traditionally associated with reusable passwords. This system also performs a secure key exchange in the process of authentication, allowing security layers (privacy and/or integrity protection) to be enabled during the session. Trusted key servers and certificate infrastructures are not required, and clients are not required to store or manage any long-term keys. SRP offers both security and deployment advantages over existing challenge-response techniques, making it an ideal drop-in replacement where secure password authentication is needed.

Note: The complete RFC2945 specification can be obtained from http://www.rfc-editor.org/rfc.html. Additional information on the SRP algorithm and its history can be found at http://www-cs-students.stanford.edu/~tjw/srp/.

SRP is similar in concept and security to other public key exchange algorithms, such as Diffie-Hellman and RSA. SRP is based on simple string passwords in a way that does not require a clear text password to exist on the server. This is in contrast to other public key-based algorithms that require client certificates and the corresponding certificate management infrastructure.

Algorithms like Diffie-Hellman and RSA are known as public key exchange algorithms. The concept of public key algorithms is that you have two keys, one public that is available to everyone, and one that is private and known only to you. When someone wants to send encrypted information to you, then encrpyt the information using your public key. Only you are able to decrypt the information using your private key. Contrast this with the more traditional shared password based encryption schemes that require the sender and receiver to know the shared password. Public key algorithms eliminate the need to share passwords.

The JBossSX framework includes an implementation of SRP that consists of the following elements:

  • An implementation of the SRP handshake protocol that is independent of any particular client/server protocol

  • An RMI implementation of the handshake protocol as the default client/server SRP implementation

  • A client side JAAS LoginModule implementation that uses the RMI implementation for use in authenticating clients in a secure fashion

  • A JMX MBean for managing the RMI server implementation. The MBean allows the RMI server implementation to be plugged into a JMX framework and externalizes the configuration of the verification information store. It also establishes an authentication cache that is bound into the JBoss server JNDI namespace.

  • A server side JAAS LoginModule implementation that uses the authentication cache managed by the SRP JMX MBean.

Figure 8.14, “The JBossSX components of the SRP client-server framework.” gives a diagram of the key components involved in the JBossSX implementation of the SRP client/server framework.

The JBossSX components of the SRP client-server framework.

Figure 8.14. The JBossSX components of the SRP client-server framework.

On the client side, SRP shows up as a custom JAAS LoginModule implementation that communicates to the authentication server through an org.jboss.security.srp.SRPServerInterface proxy. A client enables authentication using SRP by creating a login configuration entry that includes the org.jboss.security.srp.jaas.SRPLoginModule. This module supports the following configuration options:

  • principalClassName: This option is no longer supported. The principal class is now always org.jboss.security.srp.jaas.SRPPrincipal.

  • srpServerJndiName: The JNDI name of the SRPServerInterface object to use for communicating with the SRP authentication server. If both srpServerJndiName and srpServerRmiUrl options are specified, the srpServerJndiName is tried before srpServerRmiUrl.

  • srpServerRmiUrl: The RMI protocol URL string for the location of the SRPServerInterface proxy to use for communicating with the SRP authentication server.

  • externalRandomA: A true/false flag indicating if the random component of the client public key A should come from the user callback. This can be used to input a strong cryptographic random number coming from a hardware token for example.

  • hasAuxChallenge: A true/false flag indicating that a string will be sent to the server as an additional challenge for the server to validate. If the client session supports an encryption cipher then a temporary cipher will be created using the session private key and the challenge object sent as a javax.crypto.SealedObject.

  • multipleSessions: a true/false flag indicating if a given client may have multiple SRP login sessions active simultaneously.

Any other options passed in that do not match one of the previous named options is treated as a JNDI property to use for the environment passed to the InitialContext constructor. This is useful if the SRP server interface is not available from the default InitialContext.

The SRPLoginModule needs to be configured along with the standard ClientLoginModule to allow the SRP authentication credentials to be used for validation of access to security J2EE components. An example login configuration entry that demonstrates such a setup is:

srp {
    org.jboss.security.srp.jaas.SRPLoginModule required
    srpServerJndiName="SRPServerInterface"
    ;
            
    org.jboss.security.ClientLoginModule required
    password-stacking="useFirstPass"
    ;
};  

On the JBoss server side, there are two MBeans that manage the objects that collectively make up the SRP server. The primary service is the org.jboss.security.srp.SRPService MBean, and it is responsible for exposing an RMI accessible version of the SRPServerInterface as well as updating the SRP authentication session cache. The configurable SRPService MBean attributes include the following:

  • JndiName: The JNDI name from which the SRPServerInterface proxy should be available. This is the location where the SRPService binds the serializable dynamic proxy to the SRPServerInterface. If not specified it defaults to srp/SRPServerInterface.

  • VerifierSourceJndiName: The JNDI name of the SRPVerifierSource implementation that should be used by the SRPService. If not set it defaults to srp/DefaultVerifierSource.

  • AuthenticationCacheJndiName: The JNDI name under which the authentication org.jboss.util.CachePolicy implementation to be used for caching authentication information is bound. The SRP session cache is made available for use through this binding. If not specified it defaults to srp/AuthenticationCache.

  • ServerPort: RMI port for the SRPRemoteServerInterface. If not specified it defaults to 10099.

  • ClientSocketFactory: An optional custom java.rmi.server.RMIClientSocketFactory implementation class name used during the export of the SRPServerInterface. If not specified the default RMIClientSocketFactory is used.

  • ServerSocketFactory: An optional custom java.rmi.server.RMIServerSocketFactory implementation class name used during the export of the SRPServerInterface. If not specified the default RMIServerSocketFactory is used.

  • AuthenticationCacheTimeout: Specifies the timed cache policy timeout in seconds. If not specified this defaults to 1800 seconds(30 minutes).

  • AuthenticationCacheResolution: Specifies the timed cache policy resolution in seconds. This controls the interval between checks for timeouts. If not specified this defaults to 60 seconds(1 minute).

  • RequireAuxChallenge: Set if the client must supply an auxiliary challenge as part of the verify phase. This gives control over whether the SRPLoginModule configuration used by the client must have the useAuxChallenge option enabled.

  • OverwriteSessions: A flag indicating if a successful user auth for an existing session should overwrite the current session. This controls the behavior of the server SRP session cache when clients have not enabled the multiple session per user mode. The default is false meaning that the second attempt by a user to authentication will succeed, but the resulting SRP session will not overwrite the previous SRP session state.

The one input setting is the VerifierSourceJndiName attribute. This is the location of the SRP password information store implementation that must be provided and made available through JNDI. The org.jboss.security.srp SRPVerifierStoreService is an example MBean service that binds an implementation of the SRPVerifierStore interface that uses a file of serialized objects as the persistent store. Although not realistic for a production environment, it does allow for testing of the SRP protocol and provides an example of the requirements for an SRPVerifierStore service. The configurable SRPVerifierStoreService MBean attributes include the following:

  • JndiName: The JNDI name from which the SRPVerifierStore implementation should be available. If not specified it defaults to srp/DefaultVerifierSource.

  • StoreFile: The location of the user password verifier serialized object store file. This can be either a URL or a resource name to be found in the classpath. If not specified it defaults to SRPVerifierStore.ser.

The SRPVerifierStoreService MBean also supports addUser and delUser operations for addition and deletion of users. The signatures are:

public void addUser(String username, String password) throws IOException;
public void delUser(String username) throws IOException;

An example configuration of these services is presented in Section 8.6, “The Secure Remote Password (SRP) Protocol”.

8.6.1. Providing Password Information for SRP

The default implementation of the SRPVerifierStore interface is not likely to be suitable for you production security environment as it requires all password hash information to be available as a file of serialized objects. You need to provide an MBean service that provides an implementation of the SRPVerifierStore interface that integrates with your existing security information stores. The SRPVerifierStore interface is shown in.

Example 8.10. The SRPVerifierStore interface

package org.jboss.security.srp;

import java.io.IOException;
import java.io.Serializable;
import java.security.KeyException;

public interface SRPVerifierStore
{
    public static class VerifierInfo implements Serializable
    {
        /**
         * The username the information applies to. Perhaps redundant
         * but it makes the object self contained.
         */
        public String username;

        /** The SRP password verifier hash */
        public byte[] verifier;
        /** The random password salt originally used to verify the password */
        public byte[] salt;
        /** The SRP algorithm primitive generator */
        public byte[] g;
        /** The algorithm safe-prime modulus */
        public byte[] N;
    }
    
    /**
     *  Get the indicated user's password verifier information.
     */
    public VerifierInfo getUserVerifier(String username)
        throws KeyException, IOException;
    /** 
     *  Set the indicated users' password verifier information. This
     *  is equivalent to changing a user's password and should
     *  generally invalidate any existing SRP sessions and caches.
     */
    public void setUserVerifier(String username, VerifierInfo info)
        throws IOException;

    /** 
     * Verify an optional auxiliary challenge sent from the client to
     * the server.  The auxChallenge object will have been decrypted
     * if it was sent encrypted from the client. An example of a
     * auxiliary challenge would be the validation of a hardware token
     * (SafeWord, SecureID, iButton) that the server validates to
     * further strengthen the SRP password exchange.
     */
     public void verifyUserChallenge(String username, Object auxChallenge)
         throws SecurityException;
} 

The primary function of a SRPVerifierStore implementation is to provide access to the SRPVerifierStore.VerifierInfo object for a given username. The getUserVerifier(String) method is called by the SRPService at that start of a user SRP session to obtain the parameters needed by the SRP algorithm. The elements of the VerifierInfo objects are:

  • username: The user's name or id used to login.

  • verifier: This is the one-way hash of the password or PIN the user enters as proof of their identity. The org.jboss.security.Util class has a calculateVerifier method that performs that password hashing algorithm. The output password H(salt | H(username | ':' | password)) as defined by RFC2945. Here H is the SHA secure hash function. The username is converted from a string to a byte[] using the UTF-8 encoding.

  • salt: This is a random number used to increase the difficulty of a brute force dictionary attack on the verifier password database in the event that the database is compromised. It is a value that should be generated from a cryptographically strong random number algorithm when the user's existing clear-text password is hashed.

  • g: The SRP algorithm primitive generator. In general this can be a well known fixed parameter rather than a per-user setting. The org.jboss.security.srp.SRPConf utility class provides several settings for g including a good default which can obtained via SRPConf.getDefaultParams().g().

  • N: The SRP algorithm safe-prime modulus. In general this can be a well known fixed parameter rather than a per-user setting. The org.jboss.security.srp.SRPConf utility class provides several settings for N including a good default which can obtained via SRPConf.getDefaultParams().N().

So, step 1 of integrating your existing password store is the creation of a hashed version of the password information. If your passwords are already store in an irreversible hashed form, then this can only be done on a per-user basis as part of an upgrade procedure for example. Note that the setUserVerifier(String, VerifierInfo) method is not used by the current SRPSerivce and may be implemented as no-op method, or even one that throws an exception stating that the store is read-only.

Step 2 is the creation of the custom SRPVerifierStore interface implementation that knows how to obtain the VerifierInfo from the store you created in step 1. The verifyUserChallenge(String, Object) method of the interface is only called if the client SRPLoginModule configuration specifies the hasAuxChallenge option. This can be used to integrate existing hardware token based schemes like SafeWord or Radius into the SRP algorithm.

Step 3 is the creation of an MBean that makes the step 2 implementation of the SRPVerifierStore interface available via JNDI, and exposes any configurable parameters you need. In addition to the default org.jboss.security.srp.SRPVerifierStoreService example, the SRP example presented later in this chapter provides a Java properties file based SRPVerifierStore implementation. Between the two examples you should have enough to integrate your security store.

8.6.2. Inside of the SRP algorithm

The appeal of the SRP algorithm is that is allows for mutual authentication of client and server using simple text passwords without a secure communication channel. You might be wondering how this is done. If you want the complete details and theory behind the algorithm, refer to the SRP references mentioned in a note earlier. There are six steps that are performed to complete authentication:

  1. The client side SRPLoginModule retrieves the SRPServerInterface instance for the remote authentication server from the naming service.

  2. The client side SRPLoginModule next requests the SRP parameters associated with the username attempting the login. There are a number of parameters involved in the SRP algorithm that must be chosen when the user password is first transformed into the verifier form used by the SRP algorithm. Rather than hard-coding the parameters (which could be done with minimal security risk), the JBossSX implementation allows a user to retrieve this information as part of the exchange protocol. The getSRPParameters(username) call retrieves the SRP parameters for the given username.

  3. The client side SRPLoginModule begins an SRP session by creating an SRPClientSession object using the login username, clear-text password, and SRP parameters obtained from step 2. The client then creates a random number A that will be used to build the private SRP session key. The client then initializes the server side of the SRP session by invoking the SRPServerInterface.init method and passes in the username and client generated random number A. The server returns its own random number B. This step corresponds to the exchange of public keys.

  4. The client side SRPLoginModule obtains the private SRP session key that has been generated as a result of the previous messages exchanges. This is saved as a private credential in the login Subject. The server challenge response M2 from step 4 is verified by invoking the SRPClientSession.verify method. If this succeeds, mutual authentication of the client to server, and server to client have been completed. The client side SRPLoginModule next creates a challenge M1 to the server by invoking SRPClientSession.response method passing the server random number B as an argument. This challenge is sent to the server via the SRPServerInterface.verify method and server's response is saved as M2. This step corresponds to an exchange of challenges. At this point the server has verified that the user is who they say they are.

  5. The client side SRPLoginModule saves the login username and M1 challenge into the LoginModule sharedState map. This is used as the Principal name and credentials by the standard JBoss ClientLoginModule. The M1 challenge is used in place of the password as proof of identity on any method invocations on J2EE components. The M1 challenge is a cryptographically strong hash associated with the SRP session. Its interception via a third partly cannot be used to obtain the user's password.

  6. At the end of this authentication protocol, the SRPServerSession has been placed into the SRPService authentication cache for subsequent use by the SRPCacheLoginModule.

Although SRP has many interesting properties, it is still an evolving component in the JBossSX framework and has some limitations of which you should be aware. Issues of note include the following:

  • Because of how JBoss detaches the method transport protocol from the component container where authentication is performed, an unauthorized user could snoop the SRP M1 challenge and effectively use the challenge to make requests as the associated username. Custom interceptors that encrypt the challenge using the SRP session key can be used to prevent this issue.

  • The SRPService maintains a cache of SRP sessions that time out after a configurable period. Once they time out, any subsequent J2EE component access will fail because there is currently no mechanism for transparently renegotiating the SRP authentication credentials. You must either set the authentication cache timeout very long (up to 2,147,483,647 seconds, or approximately 68 years), or handle re-authentication in your code on failure.

  • By default there can only be one SRP session for a given username. Because the negotiated SRP session produces a private session key that can be used for encryption/decryption between the client and server, the session is effectively a stateful one. JBoss supports for multiple SRP sessions per user, but you cannot encrypt data with one session key and then decrypt it with another.

To use end-to-end SRP authentication for J2EE component calls, you need to configure the security domain under which the components are secured to use the org.jboss.security.srp.jaas.SRPCacheLoginModule. The SRPCacheLoginModule has a single configuration option named cacheJndiName that sets the JNDI location of the SRP authentication CachePolicy instance. This must correspond to the AuthenticationCacheJndiName attribute value of the SRPService MBean. The SRPCacheLoginModule authenticates user credentials by obtaining the client challenge from the SRPServerSession object in the authentication cache and comparing this to the challenge passed as the user credentials. Figure 8.15, “A sequence diagram illustrating the interaction of the SRPCacheLoginModule with the SRP session cache.” illustrates the operation of the SRPCacheLoginModule.login method implementation.

A sequence diagram illustrating the interaction of the SRPCacheLoginModule with the SRP session cache.

Figure 8.15. A sequence diagram illustrating the interaction of the SRPCacheLoginModule with the SRP session cache.

8.6.2.1. An SRP example

We have covered quite a bit of material on SRP and now its time to demonstrate SRP in practice with an example. The example demonstrates client side authentication of the user via SRP as well as subsequent secured access to a simple EJB using the SRP session challenge as the user credential. The test code deploys an EJB JAR that includes a SAR for the configuration of the server side login module configuration and SRP services. As in the previous examples we will dynamically install the server side login module configuration using the SecurityConfig MBean. In this example we also use a custom implementation of the SRPVerifierStore interface that uses an in memory store that is seeded from a Java properties file rather than a serialized object store as used by the SRPVerifierStoreService. This custom service is org.jboss.chap8.ex3.service.PropertiesVerifierStore. The following shows the contents of the JAR that contains the example EJB and SRP services.

[examples]$ java -cp output/classes ListJar output/chap8/chap8-ex3.jar
output/chap8/chap8-ex3.jar
+- META-INF/MANIFEST.MF
+- META-INF/ejb-jar.xml
+- META-INF/jboss.xml
+- org/jboss/chap8/ex3/Echo.class
+- org/jboss/chap8/ex3/EchoBean.class
+- org/jboss/chap8/ex3/EchoHome.class
+- roles.properties
+- users.properties
+- chap8-ex3.sar (archive)
| +- META-INF/MANIFEST.MF
| +- META-INF/jboss-service.xml
| +- META-INF/login-config.xml
| +- org/jboss/chap8/ex3/service/PropertiesVerifierStore$1.class
| +- org/jboss/chap8/ex3/service/PropertiesVerifierStore.class
| +- org/jboss/chap8/ex3/service/PropertiesVerifierStoreMBean.class
| +- org/jboss/chap8/service/SecurityConfig.class
| +- org/jboss/chap8/service/SecurityConfigMBean.class

The key SRP related items in this example are the SRP MBean services configuration, and the SRP login module configurations. The jboss-service.xml descriptor of the chap8-ex3.sar is given in Example 8.11, “The chap8-ex3.sar jboss-service.xml descriptor for the SRP services”, while Example 8.12, “The client side standard JAAS configuration” and Example 8.13, “The server side XMLLoginConfig configuration” give the example client side and server side login module configurations.

Example 8.11. The chap8-ex3.sar jboss-service.xml descriptor for the SRP services

<server>
    <!-- The custom JAAS login configuration that installs
         a Configuration capable of dynamically updating the
         config settings -->

    <mbean code="org.jboss.chap8.service.SecurityConfig" 
           name="jboss.docs.chap8:service=LoginConfig-EX3">
        <attribute name="AuthConfig">META-INF/login-config.xml</attribute>
        <attribute name="SecurityConfigName">jboss.security:name=SecurityConfig</attribute>
    </mbean>

    <!-- The SRP service that provides the SRP RMI server and server side
         authentication cache -->
    <mbean code="org.jboss.security.srp.SRPService" 
           name="jboss.docs.chap8:service=SRPService">
        <attribute name="VerifierSourceJndiName">srp-test/chap8-ex3</attribute>
        <attribute name="JndiName">srp-test/SRPServerInterface</attribute>
        <attribute name="AuthenticationCacheJndiName">srp-test/AuthenticationCache</attribute>
        <attribute name="ServerPort">0</attribute>
        <depends>jboss.docs.chap8:service=PropertiesVerifierStore</depends>
    </mbean>

    <!-- The SRP store handler service that provides the user password verifier
         information -->
    <mbean code="org.jboss.chap8.ex3.service.PropertiesVerifierStore"
           name="jboss.docs.chap8:service=PropertiesVerifierStore">
        <attribute name="JndiName">srp-test/chap8-ex3</attribute>
    </mbean>
</server>

Example 8.12. The client side standard JAAS configuration

srp {
    org.jboss.security.srp.jaas.SRPLoginModule required
    srpServerJndiName="srp-test/SRPServerInterface"
    ;
                    
    org.jboss.security.ClientLoginModule required
    password-stacking="useFirstPass"
    ;
}; 

Example 8.13. The server side XMLLoginConfig configuration

<application-policy name="chap8-ex3">
    <authentication>
        <login-module code="org.jboss.security.srp.jaas.SRPCacheLoginModule"
                      flag = "required">
            <module-option name="cacheJndiName">srp-test/AuthenticationCache</module-option>
        </login-module>
        <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule"
                      flag = "required">
            <module-option name="password-stacking">useFirstPass</module-option>
        </login-module>
    </authentication>
</application-policy>           

The example services are the ServiceConfig and the PropertiesVerifierStore and SRPService MBeans. Note that the JndiName attribute of the PropertiesVerifierStore is equal to the VerifierSourceJndiName attribute of the SRPService, and that the SRPService depends on the PropertiesVerifierStore. This is required because the SRPService needs an implementation of the SRPVerifierStore interface for accessing user password verification information.

The client side login module configuration makes use of the SRPLoginModule with a srpServerJndiName option value that corresponds to the JBoss server component SRPService JndiName attribute value(srp-test/SRPServerInterface). Also needed is the ClientLoginModule configured with the password-stacking="useFirstPass" value to propagate the user authentication credentials generated by the SRPLoginModule to the EJB invocation layer.

There are two issues to note about the server side login module configuration. First, note the cacheJndiName=srp-test/AuthenticationCache configuration option tells the SRPCacheLoginModule the location of the CachePolicy that contains the SRPServerSession for users who have authenticated against the SRPService. This value corresponds to the SRPService AuthenticationCacheJndiName attribute value. Second, the configuration includes a UsersRolesLoginModule with the password-stacking=useFirstPass configuration option. It is required to use a second login module with the SRPCacheLoginModule because SRP is only an authentication technology. A second login module needs to be configured that accepts the authentication credentials validated by the SRPCacheLoginModule to set the principal's roles that determines the principal's permissions. The UsersRolesLoginModule is augmenting the SRP authentication with properties file based authorization. The user's roles are coming the roles.properties file included in the EJB JAR.

Now, run the example 3 client by executing the following command from the book examples directory:

[examples]$ ant -Dchap=chap8 -Dex=3 run-example
...
run-example3:
     [copy] Copying 1 file to /tmp/jboss-4.0.1/server/default/deploy
     [echo] Waiting for 5 seconds for deploy...
     [java] Logging in using the 'srp' configuration
     [java] Created Echo
     [java] Echo.echo()#1 = This is call 1
     [java] Echo.echo()#2 = This is call 2

In the examples/logs directory you will find a file called ex3-trace.log. This is a detailed trace of the client side of the SRP algorithm. The traces show step-by-step the construction of the public keys, challenges, session key and verification.

Note that the client has taken a long time to run relative to the other simple examples. The reason for this is the construction of the client's public key. This involves the creation of a cryptographically strong random number, and this process takes quite a bit of time the first time it occurs. If you were to log out and log in again within the same VM, the process would be much faster. Also note that Echo.echo()#2 fails with an authentication exception. The client code sleeps for 15 seconds after making the first call to demonstrate the behavior of the SRPService cache expiration. The SRPService cache policy timeout has been set to a mere 10 seconds to force this issue. As stated earlier, you need to make the cache timeout very long, or handle re-authentication on failure.

8.7. Running JBoss with a Java 2 security manager

By default the JBoss server does not start with a Java 2 security manager. If you want to restrict privileges of code using Java 2 permissions you need to configure the JBoss server to run under a security manager. This is done by configuring the Java VM options in the run.bat or run.sh scripts in the JBoss server distribution bin directory. The two required VM options are as follows:

  • java.security.manager: This is used without any value to specify that the default security manager should be used. This is the preferred security manager. You can also pass a value to the java.security.manager option to specify a custom security manager implementation. The value must be the fully qualified class name of a subclass of java.lang.SecurityManager. This form specifies that the policy file should augment the default security policy as configured by the VM installation.

  • java.security.policy: This is used to specify the policy file that will augment the default security policy information for the VM. This option takes two forms: java.security.policy=policyFileURL and java.security.policy==policyFileURL. The first form specifies that the policy file should augment the default security policy as configured by the VM installation. The second form specifies that only the indicated policy file should be used. The policyFileURL value can be any URL for which a protocol handler exists, or a file path specification.

Both the run.bat and run.sh start scripts reference an JAVA_OPTS variable which you can use to set the security manager properties.

Enabling Java 2 security is the easy part. The difficult part of Java 2 security is establishing the allowed permissions. If you look at the server.policy file that is contained in the default configuration file set, you'll see that it contains the following permission grant statement:

grant {
    // Allow everything for now
    permission java.security.AllPermission;
};

This effectively disables security permission checking for all code as it says any code can do anything, which is not a reasonable default. What is a reasonable set of permissions is entirely up to you.

The current set of JBoss specific java.lang.RuntimePermissions that are required include:

TargetNameWhat the permission allowsRisks
org.jboss.security.SecurityAssociation.getPrincipalInfo Access to the org.jboss.security.SecurityAssociation getPrincipal() and getCredentials() methods. The ability to see the current thread caller and credentials.
org.jboss.security.SecurityAssociation.setPrincipalInfo Access to the org.jboss.security.SecurityAssociation setPrincipal() and setCredentials() methods. The ability to set the current thread caller and credentials.
org.jboss.security.SecurityAssociation.setServer Access to the org.jboss.security.SecurityAssociation setServer method. The ability to enable or disable multithread storage of the caller principal and credential.
org.jboss.security.SecurityAssociation.setRunAsRole Access to the org.jboss.security.SecurityAssociation pushRunAsRole and popRunAsRole methods. The ability to change the current caller run-as role principal.

To conclude this discussion, here is a little-known tidbit on debugging security policy settings. There are various debugging flag that you can set to determine how the security manager is using your security policy file as well as what policy files are contributing permissions. Running the VM as follows shows the possible debugging flag settings:

[bin]$ java -Djava.security.debug=help
            
all           turn on all debugging
access        print all checkPermission results
combiner      SubjectDomainCombiner debugging
jar           jar verification
logincontext  login context results
policy        loading and granting
provider      security provider debugging
scl           permissions SecureClassLoader assigns

The following can be used with access:

stack     include stack trace
domain    dumps all domains in context
failure   before throwing exception, dump stack
          and domain that didn't have permission

Note: Separate multiple options with a comma

Running with -Djava.security.debug=all provides the most output, but the output volume is torrential. This might be a good place to start if you don't understand a given security failure at all. A less verbose setting that helps debug permission failures is to use -Djava.security.debug=access,failure. This is still relatively verbose, but not nearly as bad as the all mode as the security domain information is only displayed on access failures.

8.8. Using SSL with JBoss using JSSE

JBoss uses JSEE, the Java Secure Socket Extension (JSSE), for SSL. JSSE is bundled with JDK 1.4. To get started with JSSE you need a public key/private key pair in the form of an X509 certificate for use by the SSL server sockets. For the purpose of this example we have created a self-signed certificate using the JDK keytool and included the resulting keystore file in the chap8 source directory as chap8.keystore. It was created using the following command and input:

 keytool -genkey -keystore chap8.keystore -storepass rmi+ssl -keypass rmi+ssl -keyalg RSA -alias chapter8 -validity 3650 -dname "cn=chapter8 example,ou=admin book,dc=jboss,dc=org"

This produces a keystore file called chap8.keystore. A keystore is a database of security keys. There are two different types of entries in a keystore:

  • key entries: each entry holds very sensitive cryptographic key information, which is stored in a protected format to prevent unauthorized access. Typically, a key stored in this type of entry is a secret key, or a private key accompanied by the certificate chain for the corresponding public key. The keytool and jarsigner tools only handle the later type of entry, that is private keys and their associated certificate chains.

  • trusted certificate entries: each entry contains a single public key certificate belonging to another party. It is called a trusted certificate because the keystore owner trusts that the public key in the certificate indeed belongs to the identity identified by the subject (owner) of the certificate. The issuer of the certificate vouches for this, by signing the certificate.

Listing the src/main/org/jboss/chap8/chap8.keystore examples file contents using the keytool shows one self-signed certificate:

[examples]$ keytool -list -v -keystore src/main/org/jboss/chap8/chap8.keystore
Enter keystore password:  rmi+ssl

Keystore type: jks
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: chapter8
Creation date: Dec 16, 2004
Entry type: keyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=chapter8 example, OU=admin book, DC=jboss, DC=org
Issuer: CN=chapter8 example, OU=admin book, DC=jboss, DC=org
Serial number: 41c23d6c
Valid from: Thu Dec 16 19:59:08 CST 2004 until: Sun Dec 14 19:59:08 CST 2014
Certificate fingerprints:
         MD5:  36:29:FD:1C:78:44:14:5E:5A:C7:EB:E5:E8:ED:06:86
         SHA1: 37:FE:BB:8A:A5:CF:D9:3D:B9:61:8C:53:CE:19:1E:4D:BC:C9:18:F2


*******************************************
*******************************************

With JSSE working and a keystore with the certificate you will use for the JBoss server, your are ready to configure JBoss to use SSL for EJB access. This is done by configuring the EJB invoker RMI socket factories. The JBossSX framework includes implementations of the java.rmi.server.RMIServerSocketFactory and java.rmi.server.RMIClientSocketFactory interfaces that enable the use of RMI over SSL encrypted sockets. The implementation classes are org.jboss.security.ssl.RMISSLServerSocketFactory and org.jboss.security.ssl.RMISSLClientSocketFactory respectively. There are two steps to enable the use of SSL for RMI access to EJBs. The first is to enable the use of a keystore as the database for the SSL server certificate, which is done by configuring an org.jboss.security.plugins.JaasSecurityDomain MBean. The jboss-service.xml descriptor in the chap8/ex4 directory includes the JaasSecurityDomain definition shown in Example 8.14, “A sample JaasSecurityDomain config for RMI/SSL”.

Example 8.14. A sample JaasSecurityDomain config for RMI/SSL

<!-- The SSL domain setup -->
<mbean code="org.jboss.security.plugins.JaasSecurityDomain"
       name="jboss.security:service=JaasSecurityDomain,domain=RMI+SSL">
    <constructor>
        <arg type="java.lang.String" value="RMI+SSL"/>
    </constructor>
    <attribute name="KeyStoreURL">chap8.keystore</attribute>
    <attribute name="KeyStorePass">rmi+ssl</attribute>
</mbean> 

The JaasSecurityDomain is a subclass of the standard JaasSecurityManager class that adds the notions of a keystore as well JSSE KeyManagerFactory and TrustManagerFactory access. It extends the basic security manager to allow support for SSL and other cryptographic operations that require security keys. This configuration simply loads the chap8.keystore from the example 4 MBean SAR using the indicated password.

The second step is to define an EJB invoker configuration that uses the JBossSX RMI socket factories that support SSL. To do this you need to define a custom configuration for the JRMPInvoker we saw in Chapter 5, EJBs on JBoss as well as an EJB setup that makes use of this invoker. The top of the listing shows the jboss-service.xml descriptor that defines the custom JRMPInovker

<mbean code="org.jboss.invocation.jrmp.server.JRMPInvoker"
       name="jboss:service=invoker,type=jrmp,socketType=SSL">
    <attribute name="RMIObjectPort">14445</attribute>
    <attribute name="RMIClientSocketFactory"> 
        org.jboss.security.ssl.RMISSLClientSocketFactory
    </attribute>
    <attribute name="RMIServerSocketFactory">
        org.jboss.security.ssl.RMISSLServerSocketFactory
    </attribute>
    <attribute name="SecurityDomain">java:/jaas/RMI+SSL</attribute>
    <depends>jboss.security:service=JaasSecurityDomain,domain=RMI+SSL</depends>
</mbean>

To set up an SSL invoker, we will create an invoker binding named stateless-ssl-invoker that uses our custom JRMPInvoker. We can declare the invoker binding and connect it to EchoBean4 as shown in the following jboss.xml file.

<?xml version="1.0"?>
<jboss>
    <enterprise-beans>
        <session>
            <ejb-name>EchoBean4</ejb-name>
            <configuration-name>Standard Stateless SessionBean</configuration-name>
            <invoker-bindings>
                <invoker>
                    <invoker-proxy-binding-name>
                        stateless-ssl-invoker
                    </invoker-proxy-binding-name>
                </invoker>
            </invoker-bindings>
        </session>
    </enterprise-beans>
    
    <invoker-proxy-bindings>
        <invoker-proxy-binding>
            <name>stateless-ssl-invoker</name>
            <invoker-mbean>jboss:service=invoker,type=jrmp,socketType=SSL</invoker-mbean>
            <proxy-factory>org.jboss.proxy.ejb.ProxyFactory</proxy-factory>
            <proxy-factory-config>
            <client-interceptors>
                <home>
                    <interceptor>org.jboss.proxy.ejb.HomeInterceptor</interceptor>
                    <interceptor>org.jboss.proxy.SecurityInterceptor</interceptor>
                    <interceptor>org.jboss.proxy.TransactionInterceptor</interceptor>
                    <interceptor>org.jboss.invocation.InvokerInterceptor</interceptor>
                </home>
                <bean>
                    <interceptor>org.jboss.proxy.ejb.StatelessSessionInterceptor</interceptor>
                    <interceptor>org.jboss.proxy.SecurityInterceptor</interceptor>
                    <interceptor>org.jboss.proxy.TransactionInterceptor</interceptor>
                    <interceptor>org.jboss.invocation.InvokerInterceptor</interceptor>
                </bean>
            </client-interceptors>
            </proxy-factory-config>
        </invoker-proxy-binding>
    </invoker-proxy-bindings>
</jboss>

The example 4 code is located under the src/main/org/jboss/chap8/ex4 directory of the book examples. This is another simple stateless session bean with an echo method that returns its input argument. It is hard to tell when SSL is in use unless it fails, so we'll run the example 4 client in two different ways to demonstrate that the EJB deployment is in fact using SSL. Start the JBoss server using the default configuration and then run example 4b as follows:

[examples]$ ant -Dchap=chap8 -Dex=4b run-example
...
run-example4b:
     [copy] Copying 1 file to /tmp/jboss-4.0.1/server/default/deploy
     [echo] Waiting for 15 seconds for deploy...
...
     [java] Exception in thread "main" java.rmi.ConnectIOException: error during JRMP connect
ion establishment; nested exception is: 
     [java]     javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorExceptio
n: No trusted certificate found
...            

The resulting exception is expected, and is the purpose of the 4b version of the example. Note that the exception stack trace has been edited to fit into the book format, so expect some difference. The key item to notice about the exception is it clearly shows you are using the Sun JSSE classes to communicate with the JBoss EJB container. The exception is saying that the self-signed certificate you are using as the JBoss server certificate cannot be validated as signed by any of the default certificate authorities. This is expected because the default certificate authority keystore that ships with the JSSE package only includes well known certificate authorities such as VeriSign, Thawte, and RSA Data Security. To get the EJB client to accept your self-signed certificate as valid, you need to tell the JSSE classes to use your chap8.keystore as its truststore. A truststore is just a keystore that contains public key certificates used to sign other certificates. To do this, run example 4 using -Dex=4 rather than -Dex=4b to pass the location of the correct truststore using the javax.net.ssl.trustStore system property:

[examples]$ ant -Dchap=chap8 -Dex=4 run-example
...
run-example4:
     [copy] Copying 1 file to /tmp/jboss-4.0.1/server/default/deploy
     [echo] Waiting for 5 seconds for deploy...
...
     [java] Created Echo
     [java] Echo.echo()#1 = This is call 1

This time the only indication that an SSL socket is involved is because of the SSL handshakeCompleted message. This is coming from the RMISSLClientSocketFactory class as a debug level log message. If you did not have the client configured to print out log4j debug level messages, there would be no direct indication that SSL was involved. If you note the run times and the load on your system CPU, there definitely is a difference. SSL, like SRP, involves the use of cryptographically strong random numbers that take time to seed the first time they are used. This shows up as high CPU utilization and start up times.

One consequence of this is that if you are running on a system that is slower than the one used to run the examples for the book, such as when running example 4b, you may seen an exception similar to the following:

javax.naming.NameNotFoundException: EchoBean4 not bound
   at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer
...

The problem is that the JBoss server has not finished deploying the example EJB in the time the client allowed. This is due to the initial setup time of the secure random number generator used by the SSL server socket. If you see this issue, simply rerun the example again or increase the deployment wait time in the chap8 build.xml Ant script.

8.9. Configuring JBoss for use Behind a Firewall

JBoss comes with many socket based services that open listening ports. In this section we list the services that open ports that might need to be configured to work when accessing JBoss behind a firewall. The following table shows the ports, socket type, associated service for the services in the default configuration file set. Table 8.2, “Additional ports in the all configuration” shows the same information for the additional ports that exist in the all configuration file set.

Table 8.1. The ports found in the default configuration

PortTypeService
1098TCPorg.jboss.naming.NamingService
1099TCPorg.jboss.naming.NamingService
4444TCPorg.jboss.invocation.jrmp.server.JRMPInvoker
4445TCPorg.jboss.invocation.pooled.server.PooledInvoker
8009TCPorg.jboss.web.tomcat.tc4.EmbeddedTomcatService
8080TCPorg.jboss.web.tomcat.tc4.EmbeddedTomcatService
8083TCPorg.jboss.web.WebService
8093TCPorg.jboss.mq.il.uil2.UILServerILService

Table 8.2. Additional ports in the all configuration

PortTypeService
1100TCPorg.jboss.ha.jndi.HANamingService
1101TCPorg.jboss.ha.jndi.HANamingService
1102UDPorg.jboss.ha.jndi.HANamingService
1161UDPorg.jboss.jmx.adaptor.snmp.agent.SnmpAgentService
1162 UDPorg.jboss.jmx.adaptor.snmp.trapd.TrapdService
3528TCPorg.jboss.invocation.iiop.IIOPInvoker
4447TCPorg.jboss.invocation.jrmp.server.JRMPInvokerHA
45566[a]UDPorg.jboss.ha.framework.server.ClusterPartition

[a] Plus two additional anonymous UDP ports, one can be set using the rcv_port, and the other cannot be set.

8.10. How to Secure the JBoss Server

JBoss comes with several admin access points that need to be secured or removed to prevent unauthorized access to administrative functions in a deployment. This section describes the various admin services and how to secure them.

8.10.1. The JMX Console

The jmx-console.war found in the deploy directory provides an html view into the JMX microkernel. As such, it provides access to arbitrary admin type access like shutting down the server, stopping services, deploying new services, etc. It should either be secured like any other web application, or removed.

8.10.2. The Web Console

The web-console.war found in the deploy/management directory is another web application view into the JMX microkernel. This uses a combination of an applet and a HTML view and provides the same level of access to admin functionality as the jmx-console.war. As such, it should either be secured or removed. The web-console.war contains commented out templates for basic security in its WEB-INF/web.xml as well as commented out setup for a security domain in WEB-INF/jboss-web.xml.

8.10.3. The HTTP Invokers

The http-invoker.sar found in the deploy directory is a service that provides RMI/HTTP access for EJBs and the JNDI Naming service. This includes a servlet that processes posts of marshalled org.jboss.invocation.Invocation objects that represent invocations that should be dispatched onto the MBeanServer. Effectively this allows access to MBeans that support the detached invoker operation via HTTP since one could figure out how to format an appropriate HTTP post. To security this access point you would need to secure the JMXInvokerServlet servlet found in the http-invoker.sar/invoker.war/WEB-INF/web.xml descriptor. There is a secure mapping defined for the /restricted/JMXInvokerServlet path by default, one would simply have to remove the other paths and configure the http-invoker security domain setup in the http-invoker.sar/invoker.war/WEB-INF/jboss-web.xml descriptor.

8.10.4. The JMX Invoker

The jmx-invoker-adaptor-server.sar is a service that exposes the JMX MBeanServer interface via an RMI compatible interface using the RMI/JRMP detached invoker service. The only way for this service to be secured currently would be to switch the protocol to RMI/HTTP and secure the http-invoker.sar as described in the previous section. In the future this service will be deployed as an XMBean with a security interceptor that supports role based access checks.