Previous Section Next Section

Web Services Security

e-Business relies on information exchange between trading partners over networks, often the Internet. Therefore, there are always security risks, because messages could be stolen, lost, or modified. Four security requirements must be addressed to ensure the safety of information exchange among trading partners:

  • Confidentiality guarantees that exchanged information is protected against eavesdroppers.

  • Authentication guarantees that access to e-Business applications and data is restricted to only those who can provide the appropriate proof of identity.

  • Integrity refers to assurance that the message was not modified accidentally or deliberately in transit.

  • Non-repudiation guarantees that the sender of the message cannot deny that he/she sent it.

Note that these requirements are related to cryptography because they concern how to protect communicated data. Apart from cryptography, we must also consider protection of resources such as data and applications in such a way that only appropriate entities are allowed to access the particular resources. A fifth requirement is summarized as follows:

  • Authorization is a process to decide whether the identity can access the particular resource.

In this section, we review a collection of security technologies that specifically address information exchange among trading partners via SOAP messaging. Figure 5.1 depicts a security architecture that you should keep in mind throughout this section.

Figure 5.1. Security architecture for SOAP messaging.

graphics/05fig01.gif

We begin by reviewing well-known security technologies: BASIC-AUTH and SSL. They are considered to be transport security, as shown in the figure.

Transport security is useful to some extent, but it fails to ensure non-repudiation and is not enough when you have to include third-party intermediaries. SOAP security provides transport-agnostic security measures. We will discuss digital signatures and encryption for SOAP messages.

We will introduce a non-repudiation service that ensures the delivery of the message with a timestamp. This notary third party is a good practical example of a SOAP intermediary graphics/book.gif.

Focusing on the internal process within our example company, we will describe authorization to protect resources by giving appropriate permissions to the accessing entity. We will mainly discuss role-based access control graphics/book.gif and briefly show how it can be implemented.

Finally, we will discuss Public Key Infrastructure (PKI), which provides a foundation to a solution for the four risks: confidentiality, authentication, integrity, and non-repudiation. Although PKI is a solid technology basis, it is fairly difficult to implement and use through Public Key Cryptography Standards (PKCS). We will see an emerging standard, called XML Key Management Services (XKMS) graphics/book.gif, which enables key management via XML. Let's begin by establishing the example scenario we'll use in our code samples throughout the chapter.

Example Scenario

In our discussion of security, we'll continue our SkatesTown example. SkatesTown's CTO, Dean Caroll, is beginning to become concerned with security now that the business is expanding. SkatesTown is doing business with a large number of companies, and most of them are not Fortune-500 companies. Currently, SkatesTown's Web services are secured only with SSL and BASIC-AUTH. Although Dean notices that the combination of the two is not enough, he cannot think of a better mechanism in terms of security.

To ease Dean's concern, Al Rosen of Silver Bullet Consulting was asked to advise Dean about what kind of security features to address in the next development phase. This was not an easy task for Al either, because there are numerous security technologies and specifications. It is not possible and not meaningful to cover all of them. Therefore, he selected a fairly small number of security features and applied them to SkatesTown's SOAP-based transactions, as we'll present throughout this chapter.

SSL and HTTP Basic Authentication

The most popular security method on the Internet is a combination of BASIC-AUTH and SSL. This method is widely adopted in many B2C shopping sites such as Amazon.com (http://www.amazon.com) because its configuration is fairly simple, but it still provides a necessary security level for a small amount of transactions. Here, we review BASIC-AUTH and SSL with examples of how to use them with Axis.

HTTP Basic Authentication

You probably have experienced being required to enter a user ID and password while visiting a Web site. BASIC-AUTH is often called password authentication; its specification is defined in RFC 2617 (BASIC-AUTH). The typical BASIC-AUTH interaction between a Web browser and a Web server is illustrated in Figure 5.2.

Figure 5.2. Interaction protocol for basic authentication.

graphics/05fig02.gif

When the Web browser sends an HTTP request to access a protected Web resource, the Web server returns an HTTP response, which includes the error code "401 Unauthorized" and the following HTTP header:

WWW-Authenticate: Basic realm="Realm Name"

Realmgraphics/book.gif is a name given to a set of Web resources, and it is a unit to be protected. Basic in front of realm indicates a type of authentication—in this case, BASIC-AUTH. Based on this information, the Web browser shows a login dialog to the user. Then, the Web browser sends an HTTP request again including the following HTTP header:

Authorization: Basic credential

Although the credential looks like encrypted text, it is logically plain text because its format is simply UserName:Password encoded with Base64 graphics/book.gif —for example, U2thdGVib… in Figure 5.2 can be decoded to SkateboardWarehouse:wsbookexample.

The Web server authenticates the user with the user ID and password included in the credential. If the given user ID and password are wsrong, "401 Unauthorized" is returned. Moreover, the Web server has an access control list (ACL) graphics/book.gif that specifies who can access what and checks whether the authenticated user can access the Web resource. If the check succeeds, then "200 OK" is returned; otherwise, "401 Unauthorized" is returned.

BASIC-AUTH in Axis

In this section, we review how to use BASIC-AUTH in Axis. On the server side, BASIC-AUTH is performed by middleware such as a Web server or servlet container. We do not have to modify the server programs at all, but change the server configuration. For Tomcat, we only modify its web.xml configuration file, as shown in Listing 5.1.

Listing 5.1 Configuration for Basic Authentication in Tomcat
<web-app>
   <display-name>Basic Authentication Sample</display-name>

  <servlet>
    <servlet-name>AxisServletProtected</servlet-name>
    <display-name>Apache-Axis Servlet</display-name>
    <servlet-class>org.apache.axis.transport.http.AxisServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>AxisServletProtected</servlet-name>
    <url-pattern>services/protected</url-pattern>
  </servlet-mapping>
  <security-constraint>
    <web-resource-collection>
       <web-resource-name>Protected Area</web-resource-name>
       <!-- Define the context-relative URL(s) to be protected -->
       <url-pattern>/services/protected</url-pattern>
       <!-- If you list http methods, only those methods are protected -->
       <http-method>GET</http-method>
       <http-method>POST</http-method>
    </web-resource-collection>
    <auth-constraint>
       <!-- Anyone with one of the listed roles may access this area -->
       <role-name>MyCustomer</role-name>
    </auth-constraint>
  </security-constraint>
  <login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>Protected Area</realm-name>
  </login-config>
 </web-app>

The security-constraint element defines a realm and ACL. web-resource-collection specifies a collection of Web resources, each located at url-pattern, accessed by an HTTP method like POST. auth-constraint specifies who can access the realm. login-config specifies authentication method on the realm—for example, BASIC-AUTH (indicated by BASIC).

On the client side, we have to make sure that the user ID and password are properly embedded in the HTTP request. Axis provides a basic function for performing BASIC-AUTH, so the development of the client is fairly easy. Listing 5.2 shows a POSubmission program that can access servers via BASIC-AUTH.

Listing 5.2 POSubmission that Performs Basic Authentication
package ch5.ex1;

import java.io.*;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.client.ServiceClient;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;

/**
 * Purchase order submission client
 */
public class POSubmission
{
    /**
     * Target service URL
     */
    private String url;
    private String userid;
    private String password;
    /**
     * Create a client with a target URL
     */
    public POSubmission(String targetUrl, String userid, String password)
    {
        this.url = targetUrl;
        this.userid = userid;
        this.password = password;
    }

    /**
     * Invoke the PO submission web service
     *
     * @param po Purchase order document
     * @return Invoice document
     * @exception Exception I/O error or Axis error
     */
    public String invoke(InputStream po) throws Exception
    {
        // Send the message
        ServiceClient client = new ServiceClient(url);
        client.setRequestMessage(new Message(po, true));
        call.set(Transport.USER, userid);
        call.set(Transport.PASSWORD, password);
        client.invoke();

        // Retrieve the response body
        MessageContext ctx = client.getMessageContext();
        Message outMsg = ctx.getResponseMessage();
        SOAPEnvelope envelope = outMsg.getAsSOAPEnvelope();
        SOAPBodyElement body = envelope.getFirstBody();

        // Get the XML from the body
        StringWriter w = new StringWriter();
        SerializationContext sc = new SerializationContext(w, ctx);
        body.output(sc);
        return w.toString();
    }
}

The difference from the original POSubmission (Listing 3.12) is shown in bold. Member variables userid and password are added, and they are set to the ServiceClient object in the invoke() method. As you can imagine, these values are used to create an Authorization header, with the base64 encoding of SkateboardWarehouse:wsbookexample, which is included in HTTP request. Unlike the challenge-response protocol in Figure 5.2, the HTTP request here is accepted directly because the Authorization header is included.

The new POSubmission sample can be executed with our example navigator shipped with this book. Go to /ch5/ex1/basicauth.jsp, specify a user ID and password, and click the Submit PO button (see Figure 5.3). By entering the values SkateboardWarehouse and wsbookexample, you can successfully submit the purchase order. Otherwise, you will receive an error message.

Figure 5.3. Example navigator GUI for basic authentication.

graphics/05fig03.gif

Secure Socket Layer (SSL)

BASIC-AUTH is useful, but on its own, it is not secure enough because the user ID and password are virtually unprotected. That is, an attacker can easily eavesdrop on the wire and either take the password to impersonate the user or tamper with the transmitted data.

SSL is a protocol for transmitting data in a secure way using encryption methods. With SSL, you can fulfill three of the five security requirements mentioned earlier: confidentiality, authentication, and integrity. You are probably familiar which HTTPSgraphics/book.gif, which is HTTP over SSL. However, other application layer protocols such as TELNET graphics/book.gif and FTP graphics/book.gif can be performed over SSL because SSL is located between the application layer and the transport layer (TCP).

In order to establish a secure communication channel, the server and client have to authenticate each other. With SSL, the client can authenticate the server (server authentication) and vice versa (client authentication). Currently, client authentication is not common because it requires the client to have a certificate graphics/book.gif issued by a certificate authority (CA) graphics/book.gif such as VeriSign. Instead, client authentication is often performed with BASIC-AUTH for client convenience. However, in Web services of the future, not only human clients but also business applications will also make requests, so mutual authentication by SSL will become common.

Using SSL with Axis

In this section, we review how to use SSL with Axis and address the combination of SSL server authentication and BASIC-AUTH. SSL is based on a public key cryptography system, also called an asymmetrical key cryptography system, in which separate keys are used for encryption and decryption. In the case of server authentication, the server has a private key graphics/book.gif to decrypt messages from the client, and the client has the server's public key graphics/book.gif for encrypting messages it sends after the session is established.

In the case of secret key encryption, more effort is required: Storage of the secret key by each communications partner, as well as the (initial) distribution of the secret key to those partners, must be secured. This can be a daunting and error-prone task.

You can create private and public keys using the keytool graphics/book.gif program provided with the JDK. If you add the -genkey option, the keytool command generates a private key and its public key (the command is broken here because of printing constraints, but it actually appears on a single line):

keytool -genkey -keyalg RSA –sigalg MD5withRSA -keysize 1024 -alias SkatesTown -dname 
graphics/ccc.gif"CN=Purchase Order Service, OU=Purchase Order Department, O=SkatesTown, L=..., S=NY, 
graphics/ccc.gifC=US" -keypass wsbookexample -storepass wsbookexample –keystore SkatesTown.ks -storetype 
graphics/ccc.gifJKS

The options are summarized in Table 5.1. The generated private key and related information are stored in a keystore graphics/book.gif file, and keystore file information can also be specified in the command (for example, -keystore and -storetype).

The -keyalg and -keysize options specify the specification of the private key. -dname specifies an identification (X.500 Distinguished Name graphics/book.gif) for the key, and -alias indicates an alias for the key (unique within the keystore). In addition, a password for accessing the key can be specified with -keypass (by default, it is the same as the keystore password).

A public key corresponding to the private key is also generated with this command, and is included in a certificate, which will be published to the client. Note that the certificate itself is described in more detail in PKI section. The certificate must be signed in order to demonstrate integrity. The signature algorithm is specified by the -sigalg option. Although we would like to specify who signed (or will sign) the certificate, that information cannot be specified with keytool. In this case, the certificate is signed by the private key that is generated, making it a self-signed certificate. A self-signed certificate is not practical for real use, but is sufficiently useful for the purpose of experimenting with SSL.

Table 5.1. Options for the keytool Command
Option Value Meaning
-keyalg RSA Format of the private key is RSA graphics/book.gif
-keysize 1024 Key size is 1024 bits
-alias SkatesTown Key alias is SkatesTown
-dname CN=Purchase Order Service,… Identification of the key is CN=Purchase Order Service, …
-keypass wsbookexample Password for the private key is wsbookexample
-sigalg MD5withRSA Method for signing certificate is MD5 graphics/book.gif with RSA
-storepass wsbookexample Password for the keystore file is wsbookexample
-keystore SkatesTown.ks Keystore file name is SkatesTown.ks
-keystoretype JKS Keystore file type is Java Key Store (JKS) graphics/book.gif

The generated certificate can be extracted with the following keytool command:

keytool -export -alias SkatesTown -file SkatesTown.cer -keystore SkatesTown.ks -storepass 
graphics/ccc.gifwsbookexample

The extracted certificate is stored in SkatesTown.cer. Next, we import the server certificate to a client keystore using the following command:

keytool -import -trustcacerts -alias SkatesTown -file SkatesTown.cer -keystore 
graphics/ccc.gifSkateboardWarehouse.ks -storepass wsbookexample -storetype JKS

The client uses the imported certificate to trust the server that owns that certificate. When a client establishes a session, the server sends a server certificate to the client. If the certificate is a member of the certificates included in the client keystore, the client trusts the server and so proceeds to the session.

We provide a browser interface for keytool within our example navigator. Visit /ch5/ex2/index.jsp. If you specify some parameters, keytool commands are automatically generated and executed (see Figure 5.4). You can create keystore files, export certificates, and import them to other keystore files.

Figure 5.4. Example navigator GUI for keytool.

graphics/05fig04.gif

Let's examine the SSL configuration for a Web server (Tomcat in this case). In the <tomcat-home>/conf/server.xml file, you need to add the Connector section shown in Listing 5.3.

Listing 5.3 Tomcat Configuration for SSL
<Connector className="org.apache.tomcat.service.PoolTcpConnector">
   <Parameter name="handler"
      value="org.apache.tomcat.service.http.HttpConnectionHandler"/>
   <Parameter name="port" value="8443"/>
   <Parameter name="socketFactory"
      value="org.apache.tomcat.net.SSLSocketFactory"/>
   <Parameter name="keystore"
      value="c:\ws-book\SkatesTown.ks" />
   <Parameter name="keypass" value="wsbookexample"/>
   <Parameter name="clientAuth" value="false"/>
</Connector>

HTTPS settings are specified in the Parameter elements. The port parameter indicates a port number for SSL connections. socketFactory specifies the Java factory class that will create SSL socket objects. With keystore and keypass, Tomcat can get a private key for SSL session. Note that Tomcat assumes (and hence requires) that the server's keystore password is identical to the private key password. Finally, clientAuth specifies whether client authentication is performed. Note that you have to modify <java_home>/jre/security/java.security to run Tomcat with SSL. Refer to the section "Java Secure Socket Extension" later in this chapter to learn how to modify this file and then execute Tomcat.

For the client, you must set up Java system properties that are required when invoking SSL. Listing 5.4 shows a modified POSubmission program. As you can see, the keystore type (storetype), keystore file name (keystore), and keystore password (storepass) are fed to the constructor, and the parameters are set for system properties. We will review these properties in the section "Java Secure Socket Extension." Although we specify the system parameters programmatically, you can specify them with the -D option of the java command. In that case, you do not have to change the Listing 5.2 program at all. The section "Java Secure Socket Extension" will show such an alternative example.

Listing 5.4 POSubmission that Performs Basic Authentication and SSL
package ch5.ex3;

import java.io.StringBufferInputStream;
import java.io.StringWriter;
import org.apache.axis.encoding.SerializationContext;
import org.apache.axis.message.SOAPEnvelope;
import org.apache.axis.message.SOAPBodyElement;
import org.apache.axis.client.ServiceClient;
import org.apache.axis.client.Transport;
import org.apache.axis.transport.http.HTTPTransport;
import org.apache.axis.Message;
import org.apache.axis.MessageContext;
import org.apache.axis.encoding.ServiceDescription;

final public class DoOrder {
    final String url;
    final Strint storetype;
    final Strint keystore;
    final String storepass;
    final String uid;
    final String password;

    public DoOrder(String url,
                   Strint storetype,
                   Strint keystore,
                   String storepass,
                   String uid,
                   String password)
    {
        this.url = url;
        this.storetype = storetype;
        this.keystore = keystore;
        this.storepass = storepass;
        this.uid = uid;
        this.password = password;
    }
       public synchronized static String invoke(String xml) throws Exception {
        String[][] props = {
            {  "javax.net.ssl.trustStore", keystore, },
            {  "javax.net.ssl.keyStore", keystore, },
            {  "javax.net.ssl.keyStorePassword", storepass, },
            {  "javax.net.ssl.keyStoreType", storetype, },
        };
        for (int i = 0; i < props.length; i++)
            System.getProperties().setProperty(props[i][0], props[i][1]);

              ServiceClient client = new ServiceClient(new HTTPTransport(url, "PO"));
        client.set(MessageContext.USERID, uid);
        client.set(MessageContext.PASSWORD, password);
              client.setRequestMessage(new Message(new StringBufferInputStream(xml), 
graphics/ccc.giftrue));
              client.invoke();

              Message outMsg = client.getMessageContext().getResponseMessage();
              ServiceDescription svc = new ServiceDescription("doOrder",
false);
              client.getMessageContext().setServiceDescription(svc);

              SOAPEnvelope envelope = outMsg.getAsSOAPEnvelope();
              SOAPBodyElement body = envelope.getFirstBody();
              StringWriter writer = new StringWriter();
              SerializationContext ctx = new SerializationContext(writer, 
graphics/ccc.gifclient.getMessageContext());
              body.output(ctx);
              return writer.toString();
       }
}

You can execute POSubmission with BASIC-AUTH and SSL via /ch5/ex3/index.jsp in the example navigator. Specify some values in the page, such as the keystore file, keystore password, and so on, if you want, and then click the Submit PO button (see Figure 5.5).

Figure 5.5. Example navigator GUI for basic authentication and SSL.

graphics/05fig05.gif

Java Secure Socket Extension

There is a standard API for SSL, called the Java Secure Socket Extension (JSSE)graphics/book.gif. Tomcat also uses Sun JSSE in its SSL implementation, but no additional Tomcat configuration is required. However, you do have to configure any Java Runtime Environment (JRE) that will run programs using JSSE, including Tomcat with SSL enabled. So, in the case of a Tomcat Web server, the following JSSE setup applies to the server- and client-side.

In order to use JSSE, you must first set up a security provider graphics/book.gif. The concept of a security provider is defined in the Java Cryptographic Architecture (JCA)graphics/book.gif. Because we describe JCA later, this section only explains how to configure it.

The easiest way to set up a security provider is to modify <java-home>\jre\lib\security\java.security. The file contains a list of at least one provider in the form security.provider.<n>. Add the JSSE security provider as follows:

security.provider.1=sun.security.provider.Sun
security.provider.2=com.sun.rsajca.Provider
security.provider.3=com.sun.net.ssl.internal.ssl.Provider

Next, add the three JSSE JAR files to the classpath: jsse.jar, jnet.jar, and jcert.jar. Alternatively, the files might be directly copied to the <java-home>\jre\lib\ext directory.

After JSSE configuration is finished, the client program can be executed using the following command:

java -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol 
graphics/ccc.gif-Djavax.net.ssl.trustStore=SkateboardWarehouse.ks 
graphics/ccc.gif-Djavax.net.ssl.keyStore=SkateboardWarehouse.ks 
graphics/ccc.gif-Djavax.net.ssl.keyStorePassword=wsbookexample -Djavax.net.ssl.keyStoreType=jks 
graphics/ccc.gifExamplePOClient -l https://localhost:8443/axis/servlet/AxisServlet

You might notice that the target protocol is changed from HTTP to HTTPS. The system property java.protocol.handler.pkgs enables programs to handle HTTPS in the URL class. Other system properties specify information to access a client keystore. Trusted certificates in the client keystore are examined when a server sends its certificate to determine whether the server is trusted.

The SSL Protocol

SSL was proposed by Netscape Communications and has been widely used since the explosion of the World Wide Web, because it is supported by Netscape Navigator and Microsoft Internet Explorer. The latest version of SSL, 3.0, has been presented to the Internet Engineering Task Force (IETF) graphics/book.gif for standardization. Another closely related protocol called Transport Layer Security protocol (TLS) graphics/book.gif is currently on version 1.0, published as RFC 2246. There are no major differences between SSL and TLS. TLS has not yet become widely used, so SSL 3.0 is still dominant.

Let's review the SSL protocol in more detail. Figure 5.6 illustrates how a security handshake establishes a secure connection between the client and server. Once the handshake completes, the server and client have a common secret key with which data is encrypted and decrypted. In other words, SSL uses the public key(s) to encrypt exchanges for the sole purpose of generating the shared secret key.

Figure 5.6. SSL security handshake protocol.

graphics/05fig06.gif

Despite the advantages of using public key encryption alone, SSL combines them. It does so because the public key encryption system takes more time to encrypt and decrypt messages than the secret key encryption system. Thus, the combination used by SSL takes advantage of both the easy maintenance of public key encryption and the quicker operating speed of secret key encryption.

Let's take a closer look at the SSL handshake protocol, again referring to Figure 5.6. At phase I, the client starts the handshake, and then sends a random number, a list of supported ciphers, and compression algorithms. At phase II, the server selects a cipher and a compression algorithm and notifies the client. Then it sends another random number and a server certificate (which includes a public key). At phase III, the client sends a pre-master secret to the server, encrypting it with the server public key. Finally, the client might send a client certificate. Now the handshake is completed.

The server and the client each generate a master secret by combining the random number that the server sent, the random number that the client sent, and the pre-master secret. Several secret keys are created from the master secret. For example, one is used for encrypting transmitted data, and another is used for calculating digest value of the date for integrity.

SSL ensures authentication (by verifying the certificates), confidentiality (by encrypting the data with a secret key), and integrity (by digesting the data). However, non-repudiation is not ensured with SSL because the Message Authentication Code (MAC) graphics/book.gif value of transmitted data is calculated with a common secret key.

Digital Signature

Returning to our example scenario, Dean Caroll now understands that the combination of BASIC-AUTH and SSL is a good starting point to secure SOAP-based communication with trading partner. He also understands an immediate problem with non-repudiation. Without non-repudiation, a company can repudiate its purchase order even if the company actually sent the order request, or the company can claim that the number of products is wrong. With respect to exchange of XML messages between two parties, a digital signature provides a means to prove that the sending party created the message. Al Rosen emphasized that there is already a stable version of the XML Digital Signature graphics/book.gif specification, which will become a W3C graphics/book.gif /IETF standard. Furthermore, Digital Signature for SOAP, based on the XML Digital Signature, is published as a W3C Note graphics/book.gif.

SOAP Signature Example

Currently, the Axis platform does not include signature functions, but the IBM Web Services Toolkit (WSTK) 2.4 includes signature and verification handlers for Axis. These handlers can be embedded in Axis handler chains, as shown in Figure 5.7.

Figure 5.7. Signature and verifier handlers for purchase order processing service.

graphics/05fig07.gif

In our purchase order example, the client sends a purchase order document and receives an invoice document. In practice, these two documents should be signed; otherwise, one of the parties can repudiate that it sent the document.

Figure 5.7 illustrates a handler configuration that causes both documents to be signed and verified. The signature handler at the service requestor's side signs the purchase order. On the service provider's side, the verifier handler verifies the signature of the purchase order document. The invoice is signed by the service provider and verified by the service requestor.

Listing 5.5 shows a digitally signed purchase order document. SOAP-SEC:Signature includes a signature on the purchase order and specifies a collection of parameters to create the signature. The details of this digitally signed SOAP message are described in the following section.

Listing 5.5 Purchase Order with a SOAP Digital Signature
<SOAP-ENV:Envelope
   xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header>
      <SOAP-SEC:Signature
         SOAP-ENV:actor=""
         SOAP-ENV:mustUnderstand="1"
         xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
         xmlns:SOAP-SEC="http://schemas.xmlsoap.org/soap/security/2000-12">
         <dsig:Signature xmlns:dsig="http://www.w3.org/2000/09/xmldsig#">
           <dsig:SignedInfo>
              <dsig:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/
graphics/ccc.gifREC-xml-c14n-20010315"/> <dsig:SignatureMethod Algorithm="http://www.w3.org/2000/09/
graphics/ccc.gifxmldsig#rsa-sha1"/>
              <dsig:Reference URI="#43871">
                 <dsig:Transforms>
                    <dsig:Transform Algorithm="http://www.w3.org/TR/2000/
graphics/ccc.gifCR-xml-c14n-20001026"/>
                 </dsig:Transforms>
                 <dsig:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> 
graphics/ccc.gif<dsig:DigestValue>... Base64-encoded Digest Value... </dsig:DigestValue>
              </dsig:Reference>
           </dsig:SignedInfo>
           <dsig:SignatureValue>
              ... Base64-encoded Signature Value
           </dsig:SignatureValue>
           <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
              <KeyValue>
                 <RSAKeyValue>
                    <Modulus>... Base64-encoded Modulus...</Modulus>
                    <Exponent>AQAB</Exponent>
                 </RSAKeyValue>
              </KeyValue>
              <X509Data>
                 <X509IssuerSerial>
                    <X509IssuerName> CN=Purchase Order Service OU=Purchase Order 
graphics/ccc.gifDepartment, O=SkatesTown, L=..., S=NY, C=US ....Formatted for printing </X509IssuerName>
                     <X509SerialNumber>993353832</X509SerialNumber>
                  </X509IssuerSerial>
                  <X509SubjectName> CN=Purchase Order Service, OU=Purchase Order 
graphics/ccc.gifDepartment, O=SkatesTown, L=..., S=NY, C=US ....Formatted for printing </X509SubjectName>
                  <X509Certificate>
                     ... Base64-encoded X.509 Certificate
                  </X509Certificate>
               </X509Data>
            </KeyInfo>
         </dsig:Signature>
      </SOAP-SEC:Signature>
   </SOAP-ENV:Header>
   <SOAP-ENV:Body>
      <po xmlns="http://www.skatestown.com/ns/po"
         id="43871" submitted="2001-12-06">
         ...
      </po>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The digital signature scenario can be executed with the example navigator. Go to /ch5/ex4/index.jsp, specify parameters if you want, and click the Submit PO button (see Figure 5.8).

Figure 5.8. Example navigator GUI for a digital signature.

graphics/05fig08.gif

Deployment descriptors for the example are shown in Listings 5.6 and 5.7. At the client side, request messages are signed via the sign handler, response messages are verified and logged via verify and log handlers (see Listing 5.6). At the server side, request messages are verified and logged, and response messages are signed (see Listing 5.7). As you can see in the listings, you need to specify some parameters for sign handlers, such as a keystore file, key alias, store password, and key password. On the other hand, the verify handler does not require as much information.

Listing 5.6 Deployment Descriptor for a Digital Signature at the Client
<deploy>
   <handler name="log" class="org.apache.axis.handlers.LogHandler"/>
   <handler name="sign" class="com.ibm.wstk.axis.handlers.Signer">
      <option name="alias" value="SkateboardWarehouse"/>
      <option name="keyPassword" value="wsbookexample"/>
      <option name="keyStore" value="C:\home\ryo\wsbook\examples\SkateboardWarehouse.ks" /
graphics/ccc.gif>
      <option name="keyStorePassword" value="wsbookexample"/>
   </handler>
   <handler name="verify" class="com.ibm.wstk.axis.handlers.Verifier"/>
   <service name="http://www.skatestown.com/ns/po" request="sign,log" response="log,
graphics/ccc.gifverify"/>
</deploy>
Listing 5.7 Deployment Descriptor for a Digital Signature at the Server
<deploy>
   <handler name="log" class="org.apache.axis.handlers.LogHandler"/>
   <handler name="verify" class="com.ibm.wstk.axis.handlers.Verifier"/>
   <handler name="sign" class="com.ibm.wstk.axis.handlers.Signer">
      <option name="alias" value="SkatesTown"/>
      <option name="keyPassword" value="wsbookexample"/>
      <option name="keyStore" value="C:\home\ryo\wsbook\examples\SkatesTown.ks" />
      <option name="keyStorePassword" value="wsbookexample"/>
  </handler>
  <service name="http://www.skatestown.com/ns/po" request="log,verify" 
graphics/ccc.gifpivot="MsgDispatcher" response="sign,log">
      <option name="className" value="com.skatestown.services.POSubmission"/>
       <option name="methodName" value="doSubmission"/>
   </service>
</deploy>
SOAP Signature Details

In the XML Digital Signature specification (XML Signature), an element Signature is defined with its descendants under the namespace graphics/book.gif http://www.w3.org/2000/09/xmldsig#. The SOAP Signature specification defines how to embed the Signature element in SOAP messages as a header entry. You can sign all or part of the message. Furthermore, if a message has attachments, these too can be signed. In our example, the body entry for the purchase order is signed. Let's take a closer look at our signed PO example. In the example, the target element of the signature is po:po. Briefly, the digest value of the po:po sub-tree is calculated, and the value is signed and included in the Signature element.

Let's first review how to get the digest value of the target. The target is specified by Reference under the SignedInfo element. Its URI attribute indicates the target in such a way that the id attribute of the po element is referenced. The target is transformed by XML-C14N—that is, a canonicalization graphics/book.gif method for XML. (XML Canonicalization is a W3C Recommendation to generate a canonical form for physically different but logically equivalent XML documents.) With XML-C14N, we can check whether XML documents are semantically equivalent using a standardized code set, the order of attributes, tab processing, and so on. The following two documents are quite different at a glance:

<?xml version="1.0" encoding="us-ascii"?>
<foo
   b="b"
   a="a"
></foo>

<?xml version="1.0" encoding="us-ascii"?>
<foo a="a" b="b"/>

However, with XML-C14N, they are translated into the following identical document:

<?xml version="1.0" encoding="us-ascii"?>
<foo a="a" b="b"></foo>

After translation, a digest value is calculated with an algorithm specified by the DigestMethod element. Here SHA1 graphics/book.gif is used. The calculated value is inserted in DigestValue element, represented in Base64 format.

The value of the target is not signed directly. Rather, the SignedInfo element is actually signed. An algorithm specified by the CanonicalizationMethod element—that is, XML-C14N—canonicalizes SignedInfo. The canonicalized SignedInfo is signed with an algorithm specified by SignatureMethod: RSA-SHA1. This algorithm calculates a digest value of the SignedInfo subtree, and then signs it with a RSA private key. The calculated value is inserted into the SignatureValue element, represented in Base64 format.

Optionally, the signer can include a KeyInfo element to attach key information. More specifically, the example includes an X.509 certificate, which contains a public key corresponding to the private key that signed the digest value. Because the certificate is Abstract Syntax Notation One (ASN.1) graphics/book.gif binary data, its Base64 representation is there.

So far, we have reviewed the XML Signature syntax in the signature processing process. Verification is carried out in the same manner. First, we check the value of the DigestValue element according to XML-C14N and SHA1. Next, we calculate a digest value for the SignedInfo subtree to compare it with the value in the SignatureValue element. More precisely, the signature value is decrypted with the public key, and then compared to the calculated value.

XML Encryption

SSL is useful for ensuring confidentiality. However, at least two problems exist in the context of SOAP messaging. By definition, SOAP messaging can include intermediaries, and any of them could be owned by organizations other than the service requestor or the service provider. The first problem is that any of these third parties might need to read the message. Inherently, transport-level security solutions like SSL assume that communication occurs only directly between two parties. The second problem is that SSL encrypts the whole message. In some cases, you might want to encrypt only parts of the message. SOAP Encryption can resolve these problems.

We now update our purchase order document to include card information, as shown in Listing 5.8. Instead of a BillTo element, we insert CardInfo so that the service requestor can pay with the card. When SkatesTown receives the document from the Skateboard Warehouse, it does not have to know the card information. Instead, it could just forward it to a credit company to determine if the Skateboard Warehouse is reliable in terms of the payment. SSL is not sufficient for this purpose, because SkatesTown can read the card information.

Listing 5.8 Purchase Order that Includes Card Information
<po xmlns="http://www.skatestown.com/ns/po-with-card" id="43871" submitted="2001-10-05">
.    <cardInfo>
      <name>Purchase Order Client</name>
      <company>VISA</company>
      <expiration>02/2005</expiration>
      <number>1234123412341234</number>
   </cardInfo>
   <shipTo>
      <company>The Skateboard Warehouse</company>
      <street>One Warehouse Park</street>
      <street>Building 17</street>
      <city>Boston</city>
      <state>MA</state>
      <postalCode>01775</postalCode>
   </shipTo>
   <order>
      <item sku="318-BP" quantity="5">
         <description>Skateboard backpack; five pockets</description>
      </item>
      <item sku="947-TI" quantity="12">
         <description>Street-style titanium skateboard.</description>
      </item>
      <item sku="008-PR" quantity="1000"/>
   </order>
</po>

At present, there is no standard specification for SOAP Encryption. Even the XML Encryption graphics/book.gif specification was published only very recently as a W3C Working Draft graphics/book.gif, and so is subject to change. The discussion here is based on the preliminary draft of SOAP Encryption included in WSTK 2.4. After our SOAP Encryption review, we will review the Java Cryptographic Architecture (JCA), which provides a basis for implementing SOAP Encryption and SOAP Signature.

SOAP Encryption: Syntax and Processing

Let's look at an XML Encryption example first. Listing 5.9 is an encrypted version of the purchase order document.

Listing 5.9 Encrypted Purchase Order Document
<po xmlns="http://www.skatestown.com/ns/po-with-card" id="43871" submitted="2001-10-05">
   <enc:EncryptedData
      Type="http://www.w3.org/2001/04/xmlenc#Element">
      <enc:EncryptionMethod
         Algorithm="urn:nist-gov:aes-128-cbc"/>
      <ds:KeyInfo>
         <ds:KeyName>Shared key</ds:KeyName>
      </ds:KeyInfo>
      <enc:CipherData>abCdeF...</enc:CipherData>
   </enc:EncryptedData>
   ...
</po>

This shows the simplest case, where two parties share a common secret key. Note that namespace ds is a prefix for the XML Digital Signature namespace. The XML Encryption specification reuses elements from the XML Digital Signature namespace as much as possible.

The EncryptedData element is a root element for the encrypted part, and its Type attribute indicates that the encrypted data is an XML element. The EncryptionMethod element specifies an encryption algorithm, and KeyInfo specifies a secret key. Based on the secret key and the algorithm, the card information is encrypted and stored in the CipherData element.

Listing 5.10 shows encryption with a public key.

Listing 5.10 Encryption with a Public Key
<po xmlns="http://www.skatestown.com/ns/po-with-card" id="43871" submitted="2001-10-05">
   <enc:EncryptedData
      Type="http://www.w3.org/2001/04/xmlenc#Element">
      <enc:EncryptionMethod
         Algorithm="urn:nist-gov:aes-128-cbc"/>
      <ds:KeyInfo>
         <enc:EncryptedKey>
            <enc:EncryptionMethod
               Algorithm="urn:rsadsi-com:rsa-v2.0"/>
            <ds:KeyInfo>
               <ds:KeyName>Receiver's key</ds:KeyName>
            </ds:KeyInfo>
            <enc:CipherData>ghIjkL...</enc:CipherData>
         </enc:EncryptedKey>
      </ds:KeyInfo>
      <enc:CipherData>abCdeF...</enc:CipherData>
   </enc:EncryptedData>
  ...
</po>

The idea here is that the sender generates a random secret key, encrypts the key with the receiver's public key, and encrypts the data with the secret key. Let's look at EncryptedKey first. EncryptionMethod specifies the encryption algorithm, and KeyInfo specifies the receiver's public key. Based on these elements, a secret key is encrypted to store in CipherData. Outer CipherData comes from an encryption based on the secret key and an encryption algorithm specified by the outer EncryptionAlgorithm.

Let's move on to SOAP Encryption. SOAP Encryption defines a SOAP-SEC:Encryption element, which includes a reference to the location of the encrypted data. Listing 5.11 is a sample that includes SOAP Encryption.

Listing 5.11 SOAP Encryption Example
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header>
      <SOAP-SEC:Encryption
         xmlns:SOAP-SEC="http://schemas.xmlsoap.org/soap/security/2000-12">
         <SOAP-SEC:Manifest>
            <SOAP-SEC:Reference URI="#id-0"/>
         </SOAP-SEC:Manifest>
      </SOAP-SEC:Encryption>
   </SOAP-ENV:Header>
   <SOAP-ENV:Body>
      <po xmlns="http://www.skatestown.com/ns/po-with-card" id="43871" 
graphics/ccc.gifsubmitted="2001-10-05">
         <enc:EncryptedData xmlns:enc="http://www.w3.org/2000/11/temp-xmlenc"
             Id="id-0" Type="http://www.w3.org/2001/04/xmlenc#Element">
             ...
         </enc:EncryptedData>
          ...
      </po>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The encrypted po is included in the SOAP body, adding an Id attribute to the EncryptedData element. The Id attribute is referred to by SOAP-SEC:Reference within the SOAP-SEC:Encryption header entry.

The encryption header is intended to be a directive to SOAP intermediaries. With actorURI, you can specify a particular SOAP intermediary. Therefore, you can tell the intermediary to decrypt the data, specifying where the encrypted data is located. Thus, you can embed encryption and decryption methods into the SOAP messaging path in a flexible manner.

Java Cryptography Architecture and Java Cryptography Extension

In order to implement SOAP Signature and SOAP Encryption with Java, you need to understand Java Cryptography Architecture (JCA) and Java Cryptography Extension (JCE) graphics/book.gif. JSSE is also developed on top of JCA/JCE. In this section, we review JCA/JCE in more detail to help you understand the cryptography architecture of Java.

JCA and JCE incorporate public key technologies. JCA provides a framework for accessing and developing core cryptographic functions. Implementation and algorithm independence is addressed so that applications are insulated from cryptographic details. In other words, cryptographic implementation and algorithms can be changed without modifying any application programs.

JCA provides an API for digital signature, message digest, key management, certificate management, and access control, as well as a basic security framework. The JCE API provides encryption and key exchange. The separation of the JCA and JCE APIs stems from export regulations by the United States Commerce Department.

In the section on SSL, we discussed how to configure the <java-home>\jre\lib\security\java.security file to use SSL. As we mentioned, each security provider is specified in the following format:

security.provider.<n>=<Security Provider Class>

The number indicates a priority, and the right side specifies a security provider class. Each provider class is a subclass of java.security.Provider and supports some or all parts of Java security algorithms, such as DSA, RSA, MD5, or SHA-1. For SSL, we added the third line, as follows:

security.provider.1=sun.security.provider.Sun
security.provider.2=com.sun.rsajca.Provider
security.provider.3=com.sun.net.ssl.internal.ssl.Provider

When a security algorithm is required, providers are asked whether they support the particular algorithm according to the priority. For example, if SHA1withRSA is required, the second provider is chosen. Although the second and third providers both support it, the second one has higher priority. If SSL is required, the third provider is chosen because only it supports SSL.

Combining SOAP and Transport Security

So far, we have reviewed transport-layer security (BASIC-AUTH and SSL) and SOAP-level security (SOAP Signature and SOAP Encryption). You might ask: Why do we need SOAP-level security in addition to transport-level security like SSL? The reason is related to the SOAP intermediary concept. As we reviewed in Chapter 3, SOAP messages can travel to multiple hosts, potentially relying on different transports such as HTTP and SMTP graphics/book.gif. This indirect and transport-agnostic nature of SOAP implies that transport-layer security alone is insufficient.

On the other hand, you might ask: Is transport-layer security unnecessary? In theory, we could provide a complete set of SOAP security features with which transport-layer security would no longer be needed. However, this approach will discard existing security infrastructure to some extent, and is therefore not acceptable.

SOAP-level security should be considered complementary to transport-layer security. For example, suppose that you want to send a signed message to a destination, ensuring confidentiality. No intermediary exists, and no element-wise encryption is required. In this case, why not simply use a combination of SOAP Signature and SSL? We should combine SOAP-level and transport-layer security properly considering the environment and application requirements.

Notary Service

BASIC-AUTH/SSL, SOAP Signature, and SOAP Encryption are a proper set of technologies with which you can generally fulfill the four basic security requirements: confidentiality, authentication, integrity, and non-repudiation. However, there is a further requirement: non-repudiation of message receipt. At the client side, for example, if SkatesTown receives a purchase order document from Skateboard Warehouse, it should return an invoice document. Then, it starts processing the order—that is, shipping products in the order. However, Skateboard Warehouse might not receive the invoice because of network trouble, or it might claim that the invoice was not delivered. Or, if the invoice delivery takes more than 10 days, Skateboard Warehouse can, by policy, consider the order unplaced or misplaced.

We want to ensure that the message has been received at the destination, and to know when it was received. In the context of SOAP, it might be a good idea to include a notary service as a SOAP intermediary between the trading parties, as shown in Figure 5.9. The notary service provider is trusted by both SkatesTown and their customers. When there is a disagreement on message delivery between two parties, the notary service can arbitrate the problem on the basis of its log database.

Figure 5.9. Notary service as SOAP intermediary.

graphics/05fig09.gif

From a business perspective, this structure is beneficial for three parties. Trading parties can perform business transactions safely simply by contracting with the notary service. The notary service can earn money according to the transaction volume. The only problem here is whether the notary service is a real trusted party. A number of notary services have emerged already, such as VeriSign. Most of them aim solely at trusted storage of data such as medical records. However, once they are trusted widely, they could play the role of a notary in our business structure.

What is the benefit of SOAP in Figure 5.9? We could develop the same business structure without SOAP. Flexibility is the main benefit. The Axis architecture allows trading partners to focus completely on building business-level service requestor and service provider applications, with the caveat that they must respectively produce and consume XML documents. At configuration time, handlers, potentially including handlers to invoke intermediaries, can be deployed at the requestor and/or provider side to enhance functionality or security of the message send and receipt. When these extra handlers are added, the requestor and provider applications do not have to change at all. This shows the flexibility of SOAP-based development using Axis.

Authorization

So far, we have examined security technologies with which Web services can authenticate users and protect transmitted data from eavesdropping or alteration by inappropriate parties. From a technology point of view, network security relies on cryptographic methods, such as message digests, digital signatures, and message encryption. Authorization, the security aspect covered in this section, is different from the others because it is not based on cryptography.

Authorization denotes granting authority, including granting access to resources based upon access rights. The purpose is to control access over resources, such as Web resources, databases, and so on. Perhaps the most basic implementation of this idea is the access control list (ACL), which defines a mapping from entities to resources that can be accessed by each entity. A slightly more sophisticated model is role-based access control (RBAC), which maps entities to roles and then roles to resources. This model simply adds one extra layer of abstraction to the ACL model.

Three types of authorization methods are relevant for our SOAP architecture. URL authorization controls access to Web resources such as HTML pages and servlets. Java class authorization can be implemented using the Java Authentication and Authorization Services (JAAS) graphics/book.gif package. Finally, an authenticated entity might be issued a standardized set of security assertions that describe access rights for that entity and can be shared among trading partners. These three methods are examined in detail in the remainder of this section.

URL Authorization

We have already reviewed some aspects of URL authorization in BASIC-AUTH in the Axis section. Tomcat provides a means to define user identities, user-role mapping, and role-resource mapping. The file <TOMCAT>/conf/tomcat-user.xml contains these mappings as shown in Listing 5.12.

Listing 5.12 Tomcat User File Configuration
<tomcat-users>
  <user name="SkateboardWarehouse" password="wsbookexample" roles="MyCustomer" />
  <user name="WeMakeIt" password="wsbookexample" roles="MySupplier"  />
  <user name="Both" password="wsbookexample" roles="MyCustomer,MySupplier" />

The tomcat-users element includes a collection of users, and user defines a user identity, password, and any roles assigned to it. Listing 5.13 illustrates access control for servlets.

Listing 5.13 Configuration of Access Control over Servlets
<web-app>
   <display-name>Basic Authentication Sample</display-name>
   <servlet>
      <servlet-name>PriceCheckServlet</servlet-name>
      <servlet-class>com.sams.xxxx.PriceCheckServlet</servlet-class>
   </servlet>
   <servlet>
      <servlet-name>POServlet</servlet-name>
      <servlet-class>com.sams.xxxx.POServlet</servlet-class>
   </servlet>
   <servlet-mapping>
      <servlet-name>POServlet</servlet-name>
      <url-pattern>/servlet/justsample/POServlet</url-pattern>
   </servlet-mapping>
   <servlet-mapping>
      <servlet-name>PriceCheckServlet</servlet-name>
      <url-pattern>/servlet/justsample/PriceCheckServlet</url-pattern>
   </servlet-mapping>
   <security-constraint>
      <web-resource-collection>
          <web-resource-name>Protected Area</web-resource-name>
          <url-pattern>/servlet/justsample/POServlet</url-pattern>
          <http-method>POST</http-method>
      </web-resource-collection>
      <auth-constraint>
          <role-name>MyCustomer</role-name >
      </auth-constraint>
   </security-constraint>
   <login-config>
      <auth-method>BASIC</auth-method>
      <realm-name>Protected Area</realm-name>
   </login-config>
</web-app>

The sample here is quite different from the one in the section "SSL and Basic Authentication" because we have different servlets for price checking and purchase order processing. Because Axis has a router servlet, all application classes are accessed through the router. However, if we prepare a servlet for each application class, controlling access to each of them is fairly simple, as the example demonstrates.

Access Control for Java Classes

How can we perform authorization of individual Web services within the router servlet in Axis? We have to control access to Java classes this time. Let's examine JAAS authorization over Java classes.

JAAS is an extension of the Java 2 Security Architecture (J2SA). Historically, Java security has focused on security for mobile code such as Applets. In J2SA terms, permissions are granted to a codebase, the origin of the code that is being executed. Listing 5.14 is an excerpt from <TOMCAT>/conf/tomcat.policy.

Listing 5.14 Permission Declaration in a Tomcat Policy File
// Tomcat gets all permissions
grant codeBase "file:${ tomcat.home} /lib/-" {
       permission java.security.AllPermission;
};

grant codeBase "file:${ tomcat.home} /classes/-" {
       permission java.security.AllPermission;
};

// Example webapp policy
// By default we grant read access on webapp dir and
// write in workdir
grant codeBase "file:${ tomcat.home} /webapps/examples" {
      permission java.net.SocketPermission "localhost:1024-", "listen";
      permission java.util.PropertyPermission "*", "read";
};

The first and second declarations show that Tomcat system classes are given all permissions. On the other hand, the third grant statement shows that the Tomcat example Web applications can only listen to localhost:1024 and read properties. In other words, they cannot listen to other hosts or ports, read or write files, or do any action other than those specified.

Code-based authorization is useful. But in the case of SOAP Messaging using Axis, we need authorization based on the entity that is the origin of the request, also called the (authenticated) requestor. Figure 5.10 illustrates how a JAAS-based authorization mechanism can be added to Apache Axis. Entities including bold lines are JAAS objects.

Figure 5.10. Authorization for Axis with JAAS.

graphics/05fig10.gif

The central data structure in JAAS is the subject. A subject is any entity (such as a person or company), and it is represented by a collection of security-related properties such as user ID, group, roles, employee number, and so on. These properties are called principals graphics/book.gif in J2SA. JAAS performs two major tasks: authentication and authorization. The subject is discovered and a subject with associated principals is produced at the authentication phase, and then the subject is retrieved and examined, or consumed, at the authorization phase to decide whether the subject can perform the requested action.

Let's review Figure 5.10 more closely. In Axis Engine, we first create a LoginContext and perform login to start authentication. It starts processing the order—that is, shipping products in the order. The following is a sample code:

          LoginContext lc = null;
          try {
            Subject subject = new Subject();
            Hashtable hash = new Hashtable();
            hash.put("http.username", userid); //this value should be taken from the Axis 
graphics/ccc.gifMessageContext hash.put("http.password", password); // this value is also from the 
graphics/ccc.gifmessage context
            subject.getPublicCredentials().add(hash);
            lc = new LoginContext("AxisLogin", subject);
            lc.login();
          } catch (Exception le) {}

The idea here is that an initial subject is created including BASIC-AUTH information. The user ID might be mapped to another ID for the preceding steps. When you invoke LoginContext.login(), a LoginModule is created and invoked, at which time it creates and attaches principals to the subject (in the case of the AxisLogin login module, these are Axis-specific principals). But these login modules are pluggable, so we can assume that, given our previous scenario, the MyCustomer role will be added to the subject if the HTTP username was Skateboard Warehouse.

When invoking the service, we call Subject.doAs() so that only authorized subjects will be able to perform the operation. The actual invocation looks like this:

Subject.doAs(subject,
             new AxisPrivilegedAction(uri,method));

This invocation leads us to the invocation of the run() method in AxisPrivilegedAction. Within the run() method, access permission on the associated resource (specified by a URI and method in the previous program) is checked, and the target method is invoked only if no AccessControlException is thrown. You can implement PrivilegedAction classes in any way. For example, we could have a role-action mapping database containing triples like <role, uri, method>, and our action class could check the database to authorize the given request. If the database has a triple of the form <MyCustomers,supplier:po,processpo>, a request to perform a purchase order by Skateboard Warehouse should be allowed.

We have now explored how to create an Axis authorization mechanism using JAAS. As we address enterprise application integration, we also need to consider authorization in the EJB security model. This topic will be covered in the section, "J2EE Security Model".

Security Assertions

So far, we have reviewed how to perform authorization on a single party. However, in an open e-Business world, many unfamiliar business entities might need to access our Web services. In this case, it is not desirable to set up usernames and passwords in the Web server configuration for every possible entity. In order to address authorization in this case, the idea of a security assertion is being discussed and standardized. In this section, we review the concept of a security assertion, referring to the architecture mode of the Security Assertion Markup Language (SAML) graphics/book.gif. We won't review SAML syntax because the current syntax is subject to change.

SAML defines an XML document layout specifying the following security assertions:

  • Authentication assertion

  • Attribute assertion

  • Decision assertion

These assertions are produced by their respective authorities. In some cases, the authorities are located within the same company that hosts the Web service, but they could be located anywhere on the Internet. Especially in the latter case, interoperability is important, and thus SAML is defined in the XML format.

Figure 5.11 illustrates how two parties can interact with each other via a security assertion authority. First, POClient sends a request to the authority with a user ID and password. The authority authenticates the requestor, and issues a document that contains authentication and attribute assertions. For example, the document says the requestor is the Skateboard Warehouse, and the company is ranked AA (very good). POClient sends a purchase order attaching the security assertion to POService as a SOAP header. Then, POService performs authorization, completely relying on the received assertion.

Figure 5.11. Interaction with security assertion authority.

graphics/05fig11.gif

A security assertion document is a kind of ticket. The identity of the carrier is not authenticated by the receiver. This implies the possibility of a single sign-on graphics/book.gif for distributed, multiparty Internet services. Furthermore, the ticket idea also ensures the anonymity of the requestor, because the requestor does not have to show its identity to the target service.

We can expect that standardized security assertions will have a big impact on business because with them, companies no longer have to manage authentication information on all companies they trade information with. The current world of e-Business consists solely of transactions among familiar companies. Given trusted third parties to play the role of assertion authorities, an open-ended, more flexible, and more scaleable e-Business infrastructure is possible. Standardized security assertions via conventions like SAML provides a technology basis to accomplish such a business structure.

Public Key Infrastructure and Key Management

To complete the security discussion, this section covers Public Key Infrastructure (PKI). So far, we have assumed that we can obtain the public key representing a given entity for purposes of encryption and digital signature. However, how can we know the public key is authentic and really represents the entity whose name is on it? PKI provides a basis to ensure the authenticity of all retrieved public keys.

The process that ensures key authenticity is key management, which breaks down into registration and retrieval. Recently, the XML Key Management Specification (XKMS) has been published. Directly accessing PKI requires users to do secure key generation and exchange on their own, but key management is much simpler with XKMS.

In the rest of this section, we give an overview of PKI, reviewing its key constructs, and present the XKMS standard for key management.

Public Key Infrastructure

PKI seems complicated because it combines a large number of technologies and concepts. But you only need to know that its main goal is to provide a mechanism to ensure proof of identity. The thing used to prove an identity is called a certificate. In order to manage certificates, there needs to be an issuer(s) of certificates, called a certificate authority, and a stored collection of certificates, called a certificate repository. These three constructs are central in PKI.

A certificate is a proof of identity. With a certificate, you can relate an entity to its public key. Because the certificate itself is digitally signed, you can trust its contents as long as you can trust the issuer. The X509 Certificate, which is the most popular certificate format, will be described in more detail later.

A certificate authority (CA) is an entity that issues certificates. If you can trust the CA, you can trust certificates issued by the CA. PKI assumes a fairly small number of CAs (such as VeriSign) and allows a CA to issue certificates for other CAs. As a result, certificates are organized into a hierarchy, as shown in Figure 5.12. The root is called a root CA, intermediary nodes are called subordinate CAs, and terminal nodes are called end entities. The path for an end entity to a root CA is called a certificate path graphics/book.gif. If two end entities have a common CA, they can establish trust with each other.

Figure 5.12. PKI trust model.

graphics/05fig12.gif

A certificate repository (CR) is a public database from which end entities can get certificates. Although CRs are often developed on top of a Lightweight Directory Access Protocol (LDAP) graphics/book.gif server, they can be developed in any way (for example, based on an HTTP server). Furthermore, it is still very common to omit the CR in real cases, such as when certificates are exchanged via floppy disks.

In addition, certificates can be revoked for various reasons. For example, private keys can be stolen or lost. A CA must distribute a Certificate Revocation List (CRL) graphics/book.gif to warn everyone not to accept the associated certificate as proof of identity in such cases. End entities must check the CRL as well as the certificate path.

Let's take a closer look at X.509 Certificate Version 3. Its main constructs are summarized as follows:

  • Version— Version of X.509 Certificate, such as version 3.

  • Serial Number— A unique identifier for the issuer.

  • Signature— Algorithm for digital signature, such as Sha1WithRSAEncryption.

  • Issuer— ID of the issuer specified by Distinguished Name (DN), such as "C=JP, ST=Kanagawa, L=Yamato, O=IBM, OU=TRL, CN=CA Admin/Email=caadmin@jp.ibm.com"

  • Validity— Duration of validity, specified by start and end dates.

  • Subject— ID of the owner, specified by DN.

  • Subject Public Key Info— Public key and its algorithm. A typical example of an algorithm is RSAEncryption.

You might notice that an X.509 Certificate defines only the technical details of the certificate concept—for example, that the owner (subject) and the public key are related, and the relationship is digitally signed.

XML Key Management Specification (XKMS)

From an application point of view, our immediate concern should be how to manage certificates and public keys. PKI defines a collection of operations on certificates, such as retrieval, registration, backup, revocation, recovery, and so on. With XKMS, applications can interact using PKI without focusing on the myriad of fine details in PKI such as ASN.1.

XKMS was published as a W3C Note in March 2001 by VeriSign, Microsoft, and WebMethods. XKMS has two major components: XML Key Information Service Specification (X-KISS), and XML Key Registration Service Specification (X-KRSS). One of the main goals of XKMS is to complement the emerging W3C standards, such as XML Digital Signature and XML Encryption. Actually, key information is represented by the ds:KeyInfo element defined by XML Digital Signature.

Let's examine X-KISS with a digital signature example. Listing 5.15 is a modified SOAP message including a digital signature.

Listing 5.15 SOAP Digital Signature with a Distinguished Name
<SOAP-ENV:Envelope
   xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
   <SOAP-ENV:Header>
      <SOAP-SEC:Signature
         SOAP-ENV:actor=""
         SOAP-ENV:mustUnderstand="1"
         xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
         xmlns:SOAP-SEC="http://schemas.xmlsoap.org/soap/security/2000-12">
         <dsig:Signature xmlns:dsig="http://www.w3.org/2000/09/xmldsig#">
            <dsig:SignedInfo>
                ...
            </dsig:SignedInfo>
            <dsig:SignatureValue>
               ... Base64-encoded Signature Value...
            </dsig:SignatureValue>
            <dsig:KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
               <dsig:KeyName>CN=Purchase Order Client, OU=Purchase Department, 
graphics/ccc.gifO=SkateboardWarehouse, L=..., S=NY, C=US </dsig:KeyName>
            </dsig:KeyInfo>
         </dsig:Signature>
      </SOAP-SEC:Signature>
   </SOAP-ENV:Header>
   <SOAP-ENV:Body>
      <t:po id="43871" submitted="2001-10-05">
         <t:nonce>2001-10-05T12:13:14Z</t:nonce>
.         ...
      </t:po>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The KeyName element under KeyInfo specifies only the DN of the certificate owner, and there is no longer any detailed certificate information. For signature verification, we need the public key. The key value of the public key can be retrieved via X-KISS, as in Listing 5.16.

Listing 5.16 Query for Retrieving a Key Value
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlso ap.org/soap/envelope/">
   <SOAP-ENV:Body>
      <Locate xmlns="http://www.xkms.org/schema/xkms-2001-01-20">
         <Query>
            <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
               <KeyName>CN=Purchase Order Client, OU=Purchase Department, 
graphics/ccc.gifO=SkateboardWarehouse, L=..., S=NY, C=US</KeyName>
            </KeyInfo>
         </Query>
         <Respond>
            <string>KeyValue</string>
         </Respond>
      </Locate>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The Locate element includes a query on KeyInfo, and a format of the response. This message requests a public key for the DN specified by the KeyName element. Listing 5.17 shows its response.

Listing 5.17 Response for the Key Value Query
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" >
   <SOAP-ENV:Body>
      <LocateResult xmlns="http://www.xkms.org/schema/xkms-2001-01-20">
         <Result>Success</Result>
         <Answer>
            <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
               <KeyValue>
                  <DSAKeyValue>
                     <P>
                        /X9TgR11EilS30qcLuzk5/YRt1I870QAwx4/gLZRJmlFXUAiUftZPY1Y+r/
graphics/ccc.gifF9bow9sbVWzXgTuAHTRv8mZgt2uZUKWkn5/oBHsQIsJPu6nX/rfGG/g7V+fGqKYVDwT7g/
graphics/ccc.gifbTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZndFIAcc=
                     </P>
                     <Q>l2BQjxUjC8yykrmCouuEC/BYHPU=</Q>
                     <G>
                        9+GghdabPd7LvKtcNrhXuXmUr7v6OuqC+VdMCz0HgmdRWVeOutRZT+ZxBxCBgLRJFn
                        Ej6EwoFhO3zwkyjMim4TwWeotUfI0o4KOuHiuzpnWRbqN/C/ohNWLx+2J6ASQ7zKTx
                        vqhRkImog9/hWuWfBpKLZl6Ae1UlZAFMO/7PSSo=

                     </G>
                     <Y>
                        Q9N/x1cj2LSaV9ZdKPl0Sl9HhqbBdloc/AvxvY41sQREau9s/HmPwFdTgn6iRCdXrg
                        Y2HaiQYOlBdt09UW+q2XjvY1vdrWhXlxy8VdSFEdMCla926o38igZjFqXF0LOlBKTK
                        LQTsCzWWxDB6sK8LkvaUikUFpudYa/rWP562GUI=
                     </Y>
                  </DSAKeyValue>
               </KeyValue>
            </KeyInfo>
         </Answer>
      </LocateResult>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

The value of the public key is included in KeyValue element. With this value, we can verify the signature of the initial SOAP message.

As shown in the example, X-KISS helps applications obtain cryptographic key information. In addition to key value retrieval, it can be used to validate a binding between a key name and key value. It is also useful for getting key information from an X.509 certificate. In a complementary way, X-KRSS provides key registration, revocation, and recovery services.

Although we reviewed interactions between applications and XKMS servers, how do XKMS servers interact with PKI entities such as CAs and CRs? Unfortunately, XKMS is just an interface, and therefore it does not prescribe how XKMS servers should behave. XKMS could be used to support certificate-less keys when full-featured PKI is not required. However, XKMS is most valuable if XKMS servers provide a lightweight interface to PKI. In that case, a XKMS server could cache the certificate path and CRL when it receives a key registration or retrieval request, and then periodically check the CRL to keep its database up-to-date.

One of the important aspects of XKMS is that key management functions are provided in terms of Web services. In this way, complex certificate processing logic is abstracted away from applications and into server-side components. Furthermore, key management could be administered at a single point within an entire enterprise. This is advantageous for simplifying enterprise management.

How to Get Started with Security

So far, Dean Caroll of SkatesTown has a pretty good understanding of the security architecture for SOAP and the technologies available in this area. The acceptance and maturation of each technology is quite different, however. For example, BASIC-AUTH and SSL are widely accepted, and adopting them is not a problem. On the other hand, the new SAML proposal does not even have an initial specification.

Al Rosen suggests that SkatesTown should begin with digital signatures in addition to BASIC-AUTH and SSL. A signature is immediately required for non-repudiation, and XML Signature is now a proposed recommendation. Al also recommends adding encryption and authorization once digital signatures are in place.

A working group has just been formed for XML Encryption, so its specification can still change drastically. As for authorization, we are not sure whether JAAS will be broadly accepted. We need to see how it converges with the EJB authorization model, as we described in the "EJB Security" section. SAML and non-repudiation services are under discussion, and they are worth keeping an eye on. Finally, although there are few XKMS products, you should try one of them; WSTK 2.4 includes a demonstration. XKMS can drastically decrease the workload to integrate your systems with PKI.

    Previous Section Next Section