10 Java SASL API Programming and Deployment Guide

Simple Authentication and Security Layer, or SASL, is an Internet standard (RFC 2222) that specifies a protocol for authentication and optional establishment of a security layer between client and server applications. SASL defines how authentication data is to be exchanged but does not itself specify the contents of that data. It is a framework into which specific authentication mechanisms that specify the contents and semantics of the authentication data can fit.

SASL is used by protocols, such as the Lightweight Directory Access Protocol, version 3 (LDAP v3), and the Internet Message Access Protocol, version 4 (IMAP v4) to enable pluggable authentication. Instead of hardwiring an authentication method into the protocol, LDAP v3 and IMAP v4 use SASL to perform authentication, thus enabling authentication via various SASL mechanisms.

There are a number of standard SASL mechanisms defined by the Internet community for various levels of security and deployment scenarios. These range from no security (for example, anonymous authentication) to high security (for example, Kerberos authentication) and levels in between.

The Java SASL API

The Java SASL API defines classes and interfaces for applications that use SASL mechanisms. It is defined to be mechanism-neutral: the application that uses the API need not be hardwired into using any particular SASL mechanism. The API supports both client and server applications. It allows applications to select the mechanism to use based on desired security features, such as whether they are susceptible to passive dictionary attacks or whether they accept anonymous authentication.

The Java SASL API also allows developers to use their own, custom SASL mechanisms. SASL mechanisms are installed by using the Java Cryptography Architecture (JCA); see Java Cryptography Architecture (JCA) Reference Guide.

When to Use SASL

SASL provides a pluggable authentication and security layer for network applications. There are other features in Java SE that provide similar functionality, including Java Secure Socket Extension (JSSE) (see Java Secure Socket Extension (JSSE) Reference Guide) and the Java Generic Security Service. JSSE provides a framework and an implementation for a Java language version of the SSL, TLS, and DTLS protocols. Java GSS is the Java language bindings for the Generic Security Service Application Programming Interface (GSS-API). The only mechanism currently supported underneath this API on Java SE is Kerberos v5.

With the exception of defining and building protocols from scratch, protocol definition is often the biggest factor that goes into determining which API to use. When compared with JSSE and Java GSS, SASL is relatively lightweight and is popular among some protocols. It also has the advantage that several popular, lightweight (in terms of infrastructure support) SASL mechanisms have been defined. Primary JSSE and Java GSS mechanisms, on the other hand, have relatively heavyweight mechanisms that require more elaborate infrastructures (Public Key Infrastructure and Kerberos, respectively).

SASL, JSSE, and Java GSS are often used together. For example, a common pattern is for an application to use JSSE for establishing a secure channel, and to use SASL for client, username/password-based authentication. There are also SASL mechanisms layered on top of GSS-API mechanisms; one popular example is a SASL GSS-API/Kerberos v5 mechanism that is used with LDAP.

With the exception of defining and building protocols from scratch, protocol definition is often the biggest factor in determining which API to use. For example, LDAP and IMAP are defined to use SASL, so software related to these protocols should use the Java SASL API. When building Kerberos applications and services, the API to use is Java GSS. When building applications and services that use SSL/TLS as their protocol, the API to use is JSSE.

Java SASL API Overview

SASL is a challenge-response protocol. The server issues a challenge to the client, and the client sends a response based on the challenge. This exchange continues until the server is satisfied and issues no further challenge. These challenges and responses are binary tokens of arbitrary length. The encapsulating protocol (such as LDAP or IMAP) specifies how these tokens are encoded and exchanged. For example, LDAP specifies how SASL tokens are encapsulated within LDAP bind requests and responses.

The Java SASL API is modeled according to this style of interaction and usage. It has interfaces, SaslClient and SaslServer, that represent client-side and server-side mechanisms, respectively. The application interacts with the mechanisms via byte arrays that represent the challenges and responses. The server-side mechanism iterates, issuing challenges and processing responses, until it is satisfied, while the client-side mechanism iterates, evaluating challenges and issuing responses, until the server is satisfied. The application that is using the mechanism drives each iteration. That is, it extracts the challenge or response from a protocol packet and supplies it to the mechanism, and then puts the response or challenge returned by the mechanism into a protocol packet and sends it to the peer.

Creating the Mechanisms

The client and server code that use the SASL mechanisms are not hardwired to use specific mechanism(s). In many protocols that use SASL, the server advertises (either statically or dynamically) a list of SASL mechanisms that it supports. The client then selects one of these based on its security requirements.

The Sasl class is used for creating instances of SaslClient and SaslServer. Here is an example of how an application creates a SASL client mechanism using a list of possible SASL mechanisms.

    String[] mechanisms = new String[]{"DIGEST-MD5", "PLAIN"}; 
    SaslClient sc = Sasl.createSaslClient(
        mechanisms, authzid, protocol, serverName, props, callbackHandler);

Based on the availability of the mechanisms supported by the platform and other configuration information provided via the parameters, the Java SASL framework selects one of the listed mechanisms and return an instance of SaslClient.

The name of the selected mechanism is usually transmitted to the server via the application protocol. Upon receiving the mechanism name, the server creates a corresponding SaslServer object to process client-sent responses. Here is an example of how the server would create an instance of SaslServer.

    SaslServer ss = Sasl.createSaslServer(
        mechanism, protocol, myName, props, callbackHandler);

Passing Input to the Mechanisms

Because the Java SASL API is a general framework, it must be able to accommodate many different types of mechanisms. Each mechanism needs to be initialized with input and may need input to make progress. The API provides three means by which an application gives input to a mechanism:

  1. Common input parameters: The application uses predefined parameters to supply information that are defined by the SASL specification and commonly required by mechanisms. ForSaslClient mechanisms, the input parameters are authorization id, protocol id, and server name. ForSaslServer mechanisms, the common input parameters are protocol id and (its own fully qualified) server name.

  2. Properties parameter: The application uses the properties parameter, a mapping of property names to (possibly non-string) property values, to supply configuration information. The Java SASL API defines some standard properties, such as Sasl.QOP (quality-of-protection), Sasl.STRENGTH (cipher strength), and Sasl.MAX_BUFFER (maximum buffer size). The parameter can also be used to pass in non-standard properties that are specific to particular mechanisms.

  3. Callbacks: The application uses the CallbackHandler parameter to supply input that cannot be predetermined or might not be common across mechanisms. When a mechanism requires input data, it uses the callback handler supplied by the application to collect the data, possibly from the end-user of the application. For example, a mechanism might require the end-user of the application to supply a name and password.

    Mechanisms can use the callbacks defined in the javax.security.auth.callback package; these are generic callbacks useful for building applications that perform authentication. Mechanisms might also need SASL-specific callbacks, such as those for collecting realm and authorization information, or even (non-standardized) mechanism-specific callbacks. The application should be able to accommodate a variety of mechanisms. Consequently, its callback handler must be able to service all of the callbacks that the mechanisms might request. This is not possible in general for arbitrary mechanisms, but is usually feasible due to the limited number of mechanisms that are typically deployed and used.

Using the Mechanisms

Once the application has created a mechanism, it uses the mechanism to obtain SASL tokens to exchange with the peer. The client typically indicates to the server via the application protocol which mechanism to use. Some protocols allow the client to accompany the request with an optional initial response for mechanisms that have an initial response. This feature can be used to lower the number of message exchanges required for authentication. Here is an example of how a client might use SaslClient for authentication.

    // Get optional initial response
    byte[] response = 
        (sc.hasInitialResponse() ? sc.evaluateChallenge(new byte[]) : null);

    String mechanism = sc.getMechanismName();

    // Send selected mechanism name and optional initial response to server
    send(mechanism, response);

    // Read response
    msg = receive();
    while (!sc.isComplete() && (msg.status == CONTINUE || msg.status == SUCCESS)) {
        // Evaluate server challenge
        response = sc.evaluateChallenge(msg.contents);

        if (msg.status == SUCCESS) {
            // done; server doesn't expect any more SASL data
             if (response != null) {
                throw new IOException(
                    "Protocol error: attempting to send response after completion");
            } 
            break;
        } else {
            send(mechanism, response);
            msg = receive();
        }
    }  

The client application iterates through each step of the authentication by using the mechanism (sc) to evaluate the challenge gotten from the server and to get a response to send back to the server. It continues this cycle until either the mechanism or application-level protocol indicates that the authentication has completed, or if the mechanism cannot evaluate a challenge. If the mechanism cannot evaluate the challenge, it throws an exception to indicate the error and terminates the authentication. Disagreement between the mechanism and protocol about the completion state must be treated as an error because it might indicate a compromise of the authentication exchange.

Here is an example of how a server might use SaslServer.

    // Read request that contains mechanism name and optional initial response
    msg.receive();

    // Obtain a SaslServer to perform authentication
    SaslServer ss = Sasl.createSaslServer(msg.mechanism, 
        protocol, myName, props, callbackHandler);

    // Perform authentication steps until done
    while (!ss.isComplete()) {
        try {
            // Process response
            byte[] challenge = sc.evaluateResponse(msg.contents);

            if (ss.isComplete()) {
                send(mechanism, challenge, SUCCESS);
            } else {
                send(mechanism, challenge, CONTINUE);
                msg.receive();
            } 
        } catch (SaslException e) {
            send(ERROR);
            sc.dispose();
            break;
        }
    }

The server application iterates through each step of the authentication by giving the client's response to the mechanism (ss) to process. If the response is incorrect, the mechanism indicates the error by throwing a SaslException so that the server can report the error and terminate the authentication. If the response is correct, the mechanism returns challenge data to be sent to the client and indicates whether the authentication is complete. Note that challenge data can accompany a "success" indication. This might be used, for example, to tell the client to finalize some negotiated state.

Using the Negotiated Security Layer

Some SASL mechanisms support only authentication while others support use of a negotiated security layer after authentication. The security layer feature is often not used when the application uses some other means, such as SSL/TLS, to communicate securely with the peer.

When a security layer has been negotiated, all subsequent communication with the peer must take place using the security layer. To determine whether a security layer has been negotiated, get the negotiated Sasl.QOP from the mechanism. Here is an example of how to determine whether a security layer has been negotiated.


String qop = (String) sc.getNegotiatedProperty(Sasl.QOP);
boolean hasSecurityLayer = (qop != null && 
    (qop.equals("auth-int") || qop.equals("auth-conf")));

A security layer has been negotiated if the Sasl.QOP property indicates that either integrity and/or confidentiality has been negotiated.

To communicate with the peer using the negotiated layer, the application first uses the wrap method to encode the data to be sent to the peer to produce a "wrapped" buffer. It then transfers a length field representing the number of octets in the wrapped buffer followed by the contents of the wrapped buffer to the peer. The peer receiving the stream of octets passes the buffer (without the length field) to unwrap to obtain the decoded bytes sent by the peer. Details of this protocol are described in RFC 2222. Example 10-1 illustrates how a client application sends and receives application data using a security layer.

Example 10-1 Sample Code for SASL Client Send and Receive Data


// Send outgoing application data to peer
byte[] outgoing = ...;
byte[] netOut = sc.wrap(outgoing, 0, outgoing.length);

send(netOut.length, netOut);   // send to peer

// Receive incoming application data from peer
byte[] netIn = receive();      // read length and ensuing bytes from peer

byte[] incoming = sc.unwrap(netIn, 0, netIn.length);

How SASL Mechanisms are Installed and Selected

SASL mechanism implementations are provided by SASL security providers. Each provider may support one or more SASL mechanisms and is registered with the JCA.

By default, the SunSASL provider is automatically registered as a JCA provider. To remove it or reorder its priority as a JCA provider, change the line
security.provider.7=SunSASL

in the Java security properties file (java-home/conf/security/java.security).

To add or remove a SASL provider, you add or remove the corresponding line in the security properties file. For example, if you want to add a SASL provider and have its mechanisms be chosen over the same ones implemented by the SunSASL provider, then you would add a line to the security properties file with a lower number.

security.provider.7=com.example.MyProvider
security.provider.8=SunSASL

Alternatively, you can programmatically add your own provider using the java.security.Security class. For example, the following sample code registers the com.example.MyProvider to the list of available SASL security providers.

Security.addProvider(new com.example.MyProvider());

See Step 8: Prepare for Testing in Steps to Implement and Integrate a Provider for more information about adding providers to the security properties file and programmatically adding your own providers.

When an application requests a SASL mechanism by supplying one or more mechanism names, the SASL framework looks for registered SASL providers that support that mechanism by going through, in order, the list of registered providers. The providers must then determine whether the requested mechanism matches the selection policy properties in the Sasl and if so, return an implementation for the mechanism.

The selection policy properties specify the security aspects of a mechanism, such as its susceptibility to certain attacks. These are characteristics of the mechanism (definition), rather than its implementation so all providers should come to the same conclusion about a particular mechanism. For example, the PLAIN mechanism is susceptible to plaintext attacks regardless of how it is implemented. If no selection policy properties are supplied, there are no restrictions on the selected mechanism. Using these properties, an application can ensure that it does not use unsuitable mechanisms that might be deployed in the execution environment. For example, an application might use the following sample code if it does not want to allow the use of mechanisms susceptible to plaintext attacks.

    Map<String, String> props = new HashMap<>();
    props.put(Sasl.POLICY_NOPLAINTEXT, "true");
    SaslClient sc = Sasl.createSaslClient(
        mechanisms, authzid, protocol, serverName, props, callbackHandler);

The SunSASL Provider

The SunSASL provider supports the following client and server mechanisms:

  • Client Mechanisms
    • PLAIN (RFC 2595). This mechanism supports cleartext user name/password authentication.
    • CRAM-MD5 (RFC 2195). This mechanism supports a hashed user name/password authentication scheme.
    • DIGEST-MD5 (RFC 2831). This mechanism defines how HTTP Digest Authentication can be used as a SASL mechanism.
    • EXTERNAL (RFC 2222). This mechanism obtains authentication information from an external channel (such as TLS or IPsec).
    • NTLM. This mechanism supports NTLM authentication.
  • Server Mechanisms
    • CRAM-MD5
    • DIGEST-MD5
    • NTLM

The SunSASL Provider Client Mechanisms

The SunSASL provider supports several SASL client mechanisms used in popular protocols such as LDAP, IMAP, and SMTP.

The following table summarizes the client mechanisms and their required input.

Table 10-1 SunSASL Provider Client Mechanisms

Client Mechanism Name Parameters/Input Callbacks Configuration Properties Selection Policy
CRAM-MD5 authorization id (as default user name)

PasswordCallback

NameCallback

 None

Sasl.POLICY_NOANONYMOUS

Sasl.POLICY_NOPLAINTEXT

DIGEST-MD5

authorization id

protocol id

server name

NameCallback

PasswordCallback

RealmCallback

RealmChoiceCallback

Sasl.QOP

Sasl.STRENGTH

Sasl.MAX_BUFFER

Sasl.SERVER_AUTH

javax.security.sasl.sendmaxbuffer

com.sun.security.sasl.digest.cipher