Authenticate Web Service Using SOAPHEADER


The SOAP Message Architecture

The SOAP message architecture consists of an Envelope which contains an optional Header and a compulsory Body element, as illustrated in Figure 10-5. The Body element includes the data specific to the message. The optional Header element encloses some extra information related to the message. Each child element of the Header element is called a SOAP header. You can employ SOAP headers in ASP.NET Web services to incorporate additional information with SOAP messages. As the SOAP specification doesn't strictly define the contents of a SOAP header, the header usually contains information processed by the infrastructure. <soap:Header> may be used to exchange information, such as authentication, session ID, and transaction ID. Thus, SOAP header elements are a means of extending SOAP functionality.

Figure 10-5. SOAP message architecture.

graphics/10fig05.gif

Let's create an Authenticate Web service that authenticates the user based on username and password using the SOAPHEADER base class, and develop a Web client for that Web service using Visual Studio .NET.

[View full width]
 
[View full width]
using System.Web; using System.Web.Services; using System.Web.Services.Protocols; namespace SoapHeader1 { public class Header : SoapHeader { public string Username; public string Password; } [WebService(Namespace="http://www.phptr.com")] public class AuthenticateWebService : System.Web.Services.WebService { public AuthenticateWebService () { InitializeComponent(); } //Web Service Designer generated code. [WebMethod(Description = "Using SOAP Headers in ASP.NET Web Services")][SoapHeader graphics/ccc.gif ("HeaderMemberVariable")] public string Authenticate() { // Process the SoapHeader. if (HeaderMemberVariable.Username == "Adminarun" && HeaderMemberVariable.Password == graphics/ccc.gif "Anystrongpassword") { return "Welcome! You have successfully logged in"; } return "Invalid User ID and/or Password!"; } } }
  • Create a class named Header deriving from SoapHeader and representing the data passed in the SOAP header.

  • Add two public string members ( Username; Password ) to the WebService class.

  • Add a member variable ( HeaderMemberVariable ) of the type deriving from SoapHeader .

  • Apply a SoapHeaderAttribute to the Web Service method, such as [SoapHeader("HeaderMemberVariable")] .

  • In the WebService method access the MemberName property to process the data sent in the SOAP header.

  • Check this condition: HeaderMemberVariable.Username == " Adminarun " && HeaderMemberVariable.Password == " Anystrongpassword " .

  • If it satisfies the condition, return "Welcome! You have successfully logged in" .

  • If it does not satisfy the condition, return the string "Invalid User ID and/or Password!"

  • In the test form you will notice the message "No test form is available, as this service or method does not support the HTTP GET protocol."

In the Internet Explorer test page, you can see the sample SOAP request incorporating header elements, as shown in the following code.

[View full width]
 
[View full width]
<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www graphics/ccc.gif .w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Header> <MyHeader xmlns="http://www.phptr.com/"> <Username>string</Username> <Password>string</Password> </MyHeader> </soap:Header> <soap:Body> <Authenticate xmlns="http://www.phptr.com/" /> </soap:Body> </soap:Envelope>

Creating a Proxy with Visual Studio .NET

Create an ASP.NET Web form and rename it Authenticateclient.aspx . Add two text boxes for Username and Password, a Label to display the result, and a button. After completing the GUI, add a reference to the project by clicking Project Add Web Reference. Then click the link Web References on Local Web Server or type the required service name in the address. You can view the test page, shown in Figure 10-6. Click the Add Reference button. You can view the Discovery file (DISCO) and WSDL file in the Web References node in the Solution explorer.

Figure 10-6. Add Web Reference dialog box.

graphics/10fig06.gif

CREATING A WEB FORM CLIENT

To process SOAP headers in a Web service client, the basic procedures are as follows . Create a new instance of the class representing the SOAP header.

 localhost.Header aa = new localhost.Header(); 

Assign the text box values for the SOAP header.

 aa.Username = TextBox1.Text; aa.Password = TextBox2.Text; 

Create a new instance of the proxy class.

 localhost.AuthenticateWebService proxy = new localhost.AuthenticateWebService(); 

Assign the SOAP header object to the member variable of the proxy class.

 proxy.HeaderValue = aa; 

Invoke the method on the proxy class that communicates with the Web service method, and display the result in the label control.

 string results = proxy.Authenticate(); Label1.Text =results; 

The output of the Authenticateclient.aspx is shown in Figure 10-7.

Figure 10-7. Output of Authenticateclient.asmx with correct username and password.

graphics/10fig07.gif

Again, if you transmit SOAP messages through HTTP instead of HTTPS, the client credentials will be passed as plaintext.

XML Security Technologies

XML security technologies work at the message layer, so they provide end-to-end security. XML security technologies that address the security issues are

  • XML Signature

  • XML Encryption

  • XKMS

  • SAML

Integrity

Integrity means the assurance of whether the data is tamper-proof. Integrity is achieved by employing XML Signature and hash algorithms. In using hash algorithms while transmitting the data, a hash of that data can be sent along with it. The server can then compare a hash that it computes on the received data with the hash that accompanied the received data. If the two values are equivalent, then the received data must be the same as the data from which the received hash was created. It is computed using a hashing algorithm such as Message Digest 5 (MD5) or Secure Hash Algorithm (SHA-1). One cannot reconstruct the original data from it, since hashing is a one-way process. A digital signature is nothing but an encrypted hash.

XML Signature

XML digital signature technology is a combined effort of the W3C (World Wide Web Consortium) and the IETF (Internet Engineering Task Force). The XML Signature standard facilitates signing parts of XML documents and providing end-to-end data integrity across multiple systems. An XML digital signature confirms the nonrepudiation and message integrity of transmitted XML data across Web services.

XML Signature is the foundation for XKMS, WS-Security, SAML, and other XML-related technologies that authenticate using digital signature. XML digital signatures are signatures available in the XML format that ensure authentication and originality of the parent document. A basic feature of XML signature is the ability to sign a particular portion of the XML document rather than the entire document. An XML Signature can sign more than one type of resource, such as a particular portion of an XML document, character-encoded data (HTML), and binary-encoded data (JPG).

HOW XML DIGITAL SIGNATURE OFFERS NONREPUDIATION AND INTEGRITY

By employing an XML digital signature, you can ensure that the received message is valid and has not been tampered with. With the help of the sender's private key, the service requester signs the document and sends it together with the data of the message. The service provider can then verify the signature with the sender's public key and thereby ensure message integrity.

A digital signature is created by employing the sender's private key. The private key is retained by the sender. No one except the sender can access the private key. Hence, the sender is accountable for keeping the private key private. The recipient verifies the digital signature by employing the associated public key. The public key can be used only when the private key is authentic . Thus, by using an XML digital signature, you can assure message integrity and nonrepudiation. Usually, a small portion of the document (hash or digest) rather than the entire document is transformed by employing a private key. The hashing algorithm is very sensitive to any modifications in the source document. Hence, a recipient can confirm that the document was not altered by comparing the hash that was sent to the recipient with the hash computed from the received document.

TYPES OF XML DIGITAL SIGNATURES
  • Enveloped Signatures: The generated signature is implanted within the signed XML element itself.

  • Enveloping Signatures: The generated XML digital signature enfolds the signed XML elements, which it authenticates.

  • Detached Signatures: The signed XML document and the signature are detached separately.

EXAMPLE OF AN XML DIGITAL SIGNATURE
 <?xml version='1.0'?> <!-- Detached XML Signature --> <Signature Id="MySignature" xmlns="http://www.w3.org/2000/09/xmldsig#"> <SignedInfo> <CanonicalizationMethod Algorithm= "http://www.w3.org/TR/    2001/REC-xml-c14n-20010315"/> <SignatureMethod Algorithm= "http://www.w3.org/2000/09/    xmldsig#dsa-sha1"/> <Reference URI=             "http://www.w3.org/TR/2000/    REC-xhtml1-20000126/"> <Transforms> <Transform Algorithm=       "http://www.w3.org/TR/2001/    REC-xml-c14n-20010315"/> </Transforms> <DigestMethod Algorithm=    "http://www.w3.org/2000/09/    xmldsig#sha1"/> <DigestValue>ak2r9u45n1045gan3435es503hkk8543fh68...    </DigestValue> </Reference> </SignedInfo> <SignatureValue>kf84jflk40klfk030klkdf0g55tdghdh6...    </SignatureValue> <KeyInfo>    <KeyValue>       <DSAKeyValue>           <p>...</p><X>...</X><A>...</A><Y>...</Y>       </DSAKeyValue>    </KeyValue> </KeyInfo> </Signature> 
XML SIGNATURE ELEMENTS

The Signature element is the root element of all the standard XML Digital Signatures. It contains the following three main elements.

  • SignedInfo (<SignedInfo></SignedInfo>)

  • SignatureValue (<SignatureValue></SignatureValue>)

  • KeyInfo (<KeyInfo></KeyInfo>)

Let's look at the elements of the XML signature in detail.

  • <Signature ID> attribute : This attribute identifies the signature.

  • <SignedInfo> element : This element contains all the necessary information concerning the signed resource.

  • <CanonicalizationMethod Algorithm= "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>: It is feasible that two similar XML documents may enclose the same data but diverge only in their textual representations, such as white spaces, line breaks, and element representations. Canonicalization is the process of ignoring the small variations in the XML documents so that the logically equivalent documents create the same message digest in spite of structure. Therefore, XML information sets have to be canonized before their bit representation is extracted for signature processing. This helps prevent erroneous confirmation results. The above line indicates the algorithm used for canonicalization.

  • <SignatureMethod Algorithm= "http://www.w3.org/2000/09/xmldsig#dsa-sha1"/>: This is the algorithm used for digital signature generation (convert the canonicalized SignedInfo into the SignatureValue ).

  • <Reference URI= "http://www.w3.org/TR/2000/REC-xhtml1-20000126/">: This attribute contains the location of the signed data (optional).

  • <Transforms> : This element denotes an ordered list of processing steps that were carried out on the referenced resource's content before it was digested.

  • <DigestMethod Algorithm= "http://www.w3.org/2000/09/xmldsig#sha1"/>: This attribute specifies the digest algorithm that was used (compulsory).

  • <DigestValue>ak2r9u45n1045gan3435es503hkk8543fh68...</DigestValue> : The Digest value contains the message digest generated by employing the algorithm specified in the DigestMethod Algorithm attribute.

  • <SignatureValue>kf84jflk40klfk030klkdf0g55tdghdh6...</SignatureValue> : The Signature value contains the message digest generated by employing the algorithm specified in the SignatureMethod Algorithm attribute.

  • <KeyInfo> element : This element provides references to the public key of the sender, which can then be used by the receiver to validate the digital signature and resources (optional). Normally, the KeyInfo element encloses public keys, key names , certificates and so on. In the previous example we employ a DSA type of key.

Data Protection and Privacy

Data protection is the process of offering data confidentiality and privacy. Confidentiality and privacy mean protecting the sensitive information or data from unauthorized persons. Confidentiality and privacy can be achieved by encrypting the data using a crypto-algorithm. In SSL we encrypt the entire data and send the data to one or more receivers through a secure channel. But if we want to encrypt the different parts of the same XML document separately, then XML encryption comes into the picture. By means of XML encryption, you can encrypt the needed sensitive data (portions of the message), such as credit card information, and permit header information and other data to be used for routing purposes. This facilitates end-to-end data privacy by keeping the encrypted data up to the final destination.

XML Encryption

The W3C XML Encryption Working Group, the joint effort of the W3C (World Wide Web Consortium) and the IETF (Internet Engineering Task Force), launched the XML encryption standards and specifications. In March 2002 the Working Group released the Candidate Recommendation Specification for XML encryption. XML encryption stipulates encryption syntax for XML and the process for encrypting whole or partial XML documents. XML encryption is the process of encrypting and decrypting digital XML content, using certain algorithms. The main element in the XML encryption syntax is the EncryptedData element, which, with the EncryptedKey element, is used to transport encryption keys from the creator to a known receiver.

Data to be encrypted can be arbitrary data, an XML document, an XML element, or XML element content. When an XML element or element content is encrypted, the EncryptedData element replaces the element or content, respectively, in the encrypted version of the XML document. When an entire XML document is encrypted, then the EncryptedData element may become the root of a new document or a child element in an application- chosen XML document.

XML ENCRYPTION SYNTAX

Expressed in shorthand form, the EncryptedData element has the following structure, where

  • ? denotes zero or one occurrence.

  • + denotes one or more occurrences.

  • * denotes zero or more occurrences.

The empty element tag means the element must be empty.

 <EncryptedData Id? Type?>   <EncryptionMethod/>?     <ds:KeyInfo>       <EncryptedKey>?       <AgreementMethod>?       <ds:KeyName>?       <ds:RetrievalMethod>?       <ds:*>?     </ds:KeyInfo>?     <CipherData>       <CipherValue>?       <CipherReference URI?>?     </CipherData>   <EncryptionProperties>? </EncryptedData> 

The CipherData element can either envelop or reference the raw encrypted data.

EXAMPLE OF XML ENCRYPTION SYNTAX
 <?xml version='1.0'?>   <AuthorInfo xmlns='http://objectinnovations.com/Author'>     <CompanyName>Object Innovations</CompanyName>        <Author>          <Name>G.GNANA ARUN GANESH</Name>          <Age>23</Age>          <Salary>50000</Salary>          <Department>.NET</Department>        </Author>   </AuthorInfo> 
ENCRYPTING XML ELEMENT CONTENT (ELEMENTS)

The following code shows an XML structure with the <Salary> element encrypted.

 <?xml version='1.0'?>    <AuthorInfo xmlns='http://objectinnovations.com/Author'>     <CompanyName>Object Innovations</CompanyName>      <Author>        <Name>G.GNANA ARUN GANESH</Name>        <Age>23</Age>          <EncryptedData Type='http://www.w3.org/2001/04/             xmlenc#Element' xmlns='http://www.w3.org/2001/             04/xmlenc#'>             <CipherData>                <CipherValue>A23d42U56N</CipherValue>             </CipherData>          </EncryptedData>      </Author>    </AuthorInfo> 
ENCRYPTED DOCUMENT WITH THE ENTIRE CONTENTS HIDDEN
 <?xml version='1.0'?>   <EncryptedData xmlns='http://www.w3.org/2001/04/xmlenc#' Type='http://www.isi.edu/in-notes/iana/assignments/media-types/text/xml'>     <CipherData>        <CipherValue> A23d42U56N </CipherValue>     </CipherData>   </EncryptedData> 
SUPER-ENCRYPTION: ENCRYPTING ENCRYPTEDDATA

Super-encryption enables encryption of XML documents containing sections that are already encrypted. During super-encryption of an EncryptedData or EncryptedKey element, you must encrypt the entire element. Encrypting only the content of these elements or encrypting selected child elements is invalid.

Different elements of an XML document can be encrypted separately using XML encryption. When the data is encrypted, the ciphertext is created. It is represented in base64 encoding, which uses 64 characters to represent binary data. In both enveloped and enveloping signatures, the ciphertext is stored in the CipherValue inside the CipherData element. The CipherReference references a URL of the location of the ciphertext in a detached signature.

XML Key Management Specification (XKMS)

XKMS is a specification that facilitates acquisition of key information (values, certificates, and management or trust data) from a Web service. The XKMS contains two parts:

  • XML Key Information Service Specification (X-KISS)

  • XML Key Registration Service Specification (X-KRSS)

XKMS provides an XML interface to PKI (Public Key Infrastructure), [5] including distribution, confirmation, and key management. The PKI may be based upon a different specification, such as X.509/PKIX, SPKI, or PGP. XKMS stipulates a method for XML-based clients to obtain cryptographic keys in a secured manner. A key objective of the X-KISS protocol design is to minimize the complexity of applications using XML signature. X-KRSS describes a protocol for registration of public key information.

[5] PKI is a network security architecture that offers an improved security with the help of cryptographically derived keys. PKI incorporates public key cryptography with digital signatures for authenticating users in a transaction.

Security Assertion Markup Language (SAML)

The SAML specification is an XML-based standard and messaging protocol designed to assist the secure exchange of authentication and authorization information between business partners in spite of their security systems. The Organization for the Advancement of Structured Information Standards (OASIS) establishes this emerging standard SAML (single sign-on).

SAML substitutes two previous efforts by OASIS to create an authorization and authentication protocol: S2ML and AuthXML. SAML addresses the authentication and authorization of users. SAML is designed not only for user logon to a system, but also for automated B2B transactions that need a secure transaction between the two parties. Single sign-on is the ability of the system to authenticate a client only once and permit the client to access other resources available with the same credentials.

Global XML Web Services Architecture (GXA)

Web services are built on XML, SOAP, WSDL, and Universal Description, Discovery, and Integration (UDDI) specifications. These baseline specifications offer the foundation for application integration and aggregation. But higher-level functionality, such as security, routing, reliable messaging, and transactions, have to be added to the Web services architecture to facilitate the development of Web services in real-time scenarios at the enterprise level. In April 2001 Microsoft and IBM offered an architectural sketch for the evolution of XML Web services at the W3C Workshop on Web Services to provide a solution to the current problems faced by the programmers and for the requirement of additional specifications. [6]

[6] For more information on the sketch "Security in a Web Service World: A Proposed Architecture and Roadmap," visit http://msdn.microsoft.com/ webservices /default.aspx?pull=/library/en-us/dnwssecur/html/securitywhitepaper.asp.

This sketch was the prototype of the Microsoft Global XML Web Services Architecture. The GXA [7] is a protocol framework designed to provide a consistent model for building infrastructure-level protocols for Web services and applications. Microsoft plans to submit the GXA specifications for standardization, which enables GXA as an open architecture. GXA is simply a series of modular, additional specifications that extend SOAP and facilitate the development of better real-time Web services. GXA is intended for a wide range of Web services scenarios, ranging from B2B and EAI solutions to peer-to-peer applications and B2C services.

[7] For more information on Microsoft GXA and its specifications, visit http://msdn.microsoft.com/webservices/understanding/gxa/.

GLOBAL XML WEB SERVICES SPECIFICATIONS

The GXA specifications and the definitions provided by Microsoft are as follows:

  • WS-Security: WS-Security is flexible and is designed to be used as the basis for the construction of a wide variety of security models, including PKI, Kerberos, and SSL. Particularly WS-Security provides support for multiple security tokens, multiple trust domains, multiple signature formats, and multiple encryption technologies.

  • WS-Routing: WS-Routing is a simple, stateless, SOAP-based protocol for routing SOAP messages in an asynchronous manner over a variety of transports like TCP, UDP, and HTTP.

  • WS-Inspection: The WS-Inspection specification provides an XML format for assisting in the inspection of a site for available services and a collection of rules for how inspection-related information should be made available for consumption. A WS-Inspection document provides a means for aggregating references to preexisting service description documents that have been authored in any number of formats.

  • WS-Referral: WS-Referral is a protocol that enables the routing strategies used by SOAP nodes in a message path to be dynamically configured.

  • WS-Coordination: This specification is an extensible framework for providing protocols that coordinate the actions of distributed applications. Such coordination protocols are used to support a number of applications, including those that need to reach consistent agreement on the outcome of distributed transactions.

  • WS-Transaction: This specification explains coordination types that are used with the extensible coordination framework described in the WS-Coordination specification.

  • WS-ReliableMessaging: WS-ReliableMessaging describes a protocol that allows messages to be delivered reliably between distributed applications in the presence of software component, system, or network failures.

  • WS-Addressing: WS-Addressing offers transport-neutral mechanisms to address Web services and messages.

  • WS-Attachment: This specification defines an abstract model for SOAP attachments and, based on this model, defines a mechanism for encapsulating a SOAP message and zero or more attachments in a Direct Internet Message Encapsulation (DIME) message.

Figure 10-8 shows Microsoft's Web Services Architecture (Extended Foundation).

Figure 10-8. Microsoft's Web Services Architecture (Extended Foundation).

graphics/10fig08.jpg

WS-Security

WS-Security [8] is a specification that facilitates development of secure Web services. On April 11, 2002, IBM, Microsoft, and VeriSign jointly developed a specification for Web Services Security (WS-Security). The specification aims to help enterprises build secure and broadly interoperable Web services and applications. Even though WS-Security doesn't offer an absolute solution to the security problems, it provides a way to build other specifications, keeping WS-Security as groundwork . Figure 10-9 illustrates the evolving WS-Security Roadmap.

[8] For more information on the WS-Security specification and for the latest specifications, visit http://msdn.microsoft.com/webservices/understanding/default.aspx?pull=/library/en-us/dnglobspec/html/wssecurspecindex.asp.

Figure 10-9. Evolving WS-Security Roadmap.

graphics/10fig09.jpg

WS-Security is a baseline specification and assists in sending secure messages. It explains how to attach security tokens, including binary security tokens such as X.509 certificates and Kerberos tickets, to SOAP messages.

WS Initial Specifications

WS-SECURITY

WS-Security is a specification that provides different ways of authentication by attaching signature and encryption header elements to SOAP messages that facilitate protection of the integrity and confidentiality of messages exchanged between business applications.

WS-POLICY

WS-Policy is a specification that describes the capabilities of the security policies on intermediaries and endpoints (e.g., required security tokens, supported encryption algorithms, privacy rules). It describes the business, security, trust, and privacy policies that manage how business applications integrate with one another. The WS-Policy has been further refined to include four documents: Web Services Policy Framework (WS-Policy), Web Services Policy Attachment (WS-PolicyAttachment), Web Services Policy Assertions Language (WS-PolicyAssertions), and Web Services Security Policy (WS-Security Policy). WS-SecurityPolicy was published as a public specification on December 18, 2002.

WS-TRUST

WS-Trust defines extensions that build on WS-Security to request and issue security tokens, and it defines how to manage trust relationships between businesses. It is a specification that defines a framework for trust models that enable Web services to interoperate securely. WS-Trust was published as a public specification on December 18, 2002.

WS-SECURE CONVERSATION

WS-SecureConversation is a specification that describes how to control and authenticate message exchanges between Web services and clients, including security context exchange in a complex business transaction. WS-SecureConversation was published as a public specification on December 18, 2002.

WS-FEDERATION

WS-Federation is a specification that defines mechanisms that are used to enable identity, account, attribute, authentication, and authorization federation across different trust realms. WS-Federation explains a model for integrating mismatched security mechanisms (e.g., one party using PKI system and another one using Kerberos system) or similar mechanisms (e.g., both parties using Kerberos system) that are deployed within different domains. WS-Federation and the Federation profiles (WS-Federation Active Requestor Profile and WS-Federation Passive Requestor Profile) were published as public specifications on July 8, 2003.

Next Steps of Specifications

These Web services specifications are in the works under OASIS.

WS-PRIVACY

WS-Privacy is a specification that describes how Web services and requesters specify privacy policies and preferences.

WS-AUTHORIZATION

WS-Authorization facilitates the management of authorization data and authorization policies.

Why WS-Security?

As we discussed, present HTTP-based and HTTPS-based security offers point-to-point security only. But real-time Web services need end-to-end security. The data security and integrity have to be protected over multiple hops. WS-Security addresses how to maintain a secure context over a multipoint message path and provide an end-to-end security. Moreover, WS-Security is flexible and extensible. It incorporates a wide variety of existing security models and encryption technologies.

WS-SECURITY IN DETAIL

WS-Security makes use of various familiar and existing security standards and specifications. WS-Security facilitates the combination of current, existing security standards, such as Kerberos, PKI, XML Encryption, XML Signature, and SSL, for securing Web services. WS-Security offers a framework to implant the existing technologies into a SOAP message in a transport-neutral fashion. WS-Security also supports propagating security tokens, such as X.509 certificates and Kerberos tickets, along with multiple security tokens across multiple trust domains by employing multiple signature formats and multiple encryption technologies.

In WS-Security the SOAP header element is employed to transmit security-related data. For example, when an XML signature is used, the header can enclose information such as the key type used, and signature value. Likewise, the header contains encryption information when we employ XML encryption. Thus, the WS-Security indicates how to implant the security information provided by other specifications within a SOAP message instead of specifying the format.

Apart from implementing the existing security specifications in the SOAP header, WS-Security spells out a method by which we can transmit simple user credentials through the UsernameToken element. It also defines how to send binary tokens. As all the security information is enclosed in the SOAP part of the message, WS-Security provides end-to-end security for Web services. WS-Security provides enrichments to the existing SOAP messaging to offer quality of protection. Figure 10-10 illustrates the SOAP message format. For securing Web services, WS-Security offers three key mechanisms:

  • Security token propagation

  • Message integrity

  • Message confidentiality

Figure 10-10. SOAP message format in WS-Security.

graphics/10fig10.gif

Security Token Propagation

In this standard mechanism the security token is incorporated into the SOAP message. Security token propagation means the security credentials are transmitted from a sender to a receiver. The sender and receiver may be the client, the XML Web service, or an intermediary. Since the token is included with the SOAP message, it is transparent to the outside world. The possibility of tampering with the security tokens by intermediaries is high, as the security token is in cleartext. Proper safety measures have to be taken by employing message integrity and message confidentiality. WS-Security offers only a general-purpose mechanism for associating the token with the SOAP message. It doesn't demand a particular type of security token. It is flexible and supports a variety of security tokens.

The necessary security-related information, including security tokens, are added to a <Security> SOAP header for the targeted receiver (SOAP actor) by the client or intermediaries. If the security-related information present in the SOAP message is valid, then the request is accepted; otherwise , it is rejected. A SOAP message, before reaching the receiver, can contain zero or more <Security> SOAP headers, since the SOAP message is routed via multiple intermediaries.

WS-SECURITY EXAMPLE

The following sample SOAP message with a <Security> SOAP header illustrates a message sender's credentials (X.509 certificate) for the recipient http://www.arunmicrosystems.netfirms.com/Gnv.asmx .

 <S:Envelope xmlns:S="http://www.w3.org/2001/12/soap-envelope" xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/04/secext">     <S:Header>            ...        <wsse:Security S:actor=" http://www.arunmicrosystems.netfirms.com/Gnv.asmx " >           <wsse:BinarySecurityToken xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/04/secext"               ValueType="wsse:X509v3"               wsu:Id="X509Token"               EncodingType="wsse:Base64Binary">               AwSaRgguTQmVkopX...           </wsse:BinarySecurityToken>        </wsse:Security>             ...     </S:Header>     ... </S:Envelope> 

The namespaces used in the WS-Security document are shown in Table 10-2.

Table 10-2. Namespaces Used in WS-Security

Prefix

Namespace

S

http://www.w3.org/2001/12/soap-envelope

Ds

http://www.w3.org/2000/09/xmldsig#

Xenc

http://www.w3.org/2001/04/xmlenc#

M

http://schemas.xmlsoap.org/rp

Wsse

http://schemas.xmlsoap.org/ws/2002/07/secext

Wsu

http://schemas.xmlsoap.org/ws/2002/07/utility

Any recipient can use the security-related information within the <Security> header if the actor attribute is absent. The <Security> header block contains the security-related information for the message.

 <wsse:BinarySecurityToken ... </wsse:BinarySecurityToken> 

The previous code denotes a security token that is associated with the message. In this case we specify an X.509 certificate that is encoded as base64.

Message Integrity

WS-Security defines a mechanism by which the recipients can confirm whether the message originated from the appropriate sender and the message was not tampered with during the transit. For this purpose WS-Security employs the XML Signature specification. The integrity mechanisms are designed to support multiple signatures, potentially by multiple actors, and to be extensible to support additional signature formats. As we discussed, the XML Signature specification defines a <Signature> element along with subelements for specifying the details of a signature.

WS-Security builds upon this XML Signature, incorporating a <SecurityTokenReference> element and a <Signature> element to reference the security token specified in the <Security> SOAP header. With the contents of the SOAP message and the security token, the XML Signature is cryptographically computed. The message recipient verifies the validity of the signature by employing a cryptographic decoding algorithm.

The following SOAP message with a <SecurityTokenReference> element illustrates the addition of an XML Signature to a SOAP message.

 <S:Envelope xmlns:S="http://www.w3.org/2001/12/soap-envelope" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" mlns:wsse="http://schemas.xmlsoap.org/ws/2002/04/secext" >    <S:Header>       <wsse:Security>          <wsse:BinarySecurityToken                      ValueType="wsse:X509v3"                      EncodingType="wsse:Base64Binary"                      wsu:Id="X509Token">                  AwSaRgguTQmVkopX...          </wsse:BinarySecurityToken>          <ds:Signature>             ...             <ds:KeyInfo>                 <wsse:SecurityTokenReference>                     <wsse:Reference URI="#X509Token"/>                 </wsse:SecurityTokenReference>             </ds:KeyInfo>          </ds:Signature>       </wsse:Security>    </S:Header>    ... </S:Envelope> 

The signature is computed based on the X.509 certificate, which is specified in the <Security> header.

Message Confidentiality

We discussed how to implement message integrity and how to propagate security tokens by employing WS-Security. But integrity and authentication alone are not sufficient. Imagine a scenario in which the sent message containing sensitive information is both authenticated and signed but not encrypted. What might happen? The attacker could easily access the sensitive information and verify whether it is tamper-proof (confirms no other attacker has modified the message) and from the appropriate sender! So, it is necessary to encrypt the message. During encryption, you can employ either symmetric or asymmetric encryption according to the situation. WS-Security defines a mechanism to make sure the SOAP message is confidential between the sender and receiver. WS-Security employs this by using the XML encryption standard to encrypt portions of the SOAP message. It describes how the <ReferenceList>, <EncryptedData>, <EncryptedKey> , and <DataReference> elements defined by XML encryption can be used in the <Security> header.

The following code encrypts the body of a SOAP message using a secret key shared by the sender and receiver.

 <S:Envelope    xmlns:S="http://www.w3.org/2001/12/soap-envelope"    xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:wsse="http://schemas.xmlsoap.org/ws/2002/04/secext"    xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">     <S:Header>         <wsse:Security>             <xenc:ReferenceList>                 <xenc:DataReference URI="#enc1"/>             </xenc:ReferenceList>         </wsse:Security>     </S:Header> <S:Body> <xenc:EncryptedData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:wsu="http://schemas.xmlsoap.org/ws/2002/07/utility" Type="http://www.w3.org/2001/04/xmlenc#Element" wsu:Id="enc1">     <xenc:EncryptionMethod     Algorithm="http://www.w3.org/2001/04/xmlenc#3des-cbc"/>          <xenc:CipherData>               <xenc:CipherValue>dwSaRgguTQmVkopX...               </xenc:CipherValue>          </xenc:CipherData> </xenc:EncryptedData> </S:Body> </S:Envelope> 

An overview of the Web services security standards is shown in Table 10-3.

Table 10-3. Web Services Security Standards

Technology

Security Function

Description

Basic HTTP

Authentication

HTTP and its security mechanisms address only point-to-point security.

HTTPS ( SSL 3.0/ TLS 1.0)

Confidentiality, data integrity, and authentication (encryption)

Point-to-point security sessions between client and server.

XML Signature

Authentication, integrity, and nonrepudiation (authentication)

Prerequisite for WS-Security. It ensures the received message is tamper-proof.

XML Encryption

Integrity and privacy (encryption)

Prerequisite for WS-Security. It prevents the attacker from reading the content of the XML message.

XML Key Management Specification ( XKMS )

Authentication, privacy, and integrity (key exchange)

XKMS provides an XML interface to PKI, including distribution, confirmation, and key management.

Security Assertion Markup Language ( SAML )

Authentication and authorization

Provides interoperable authentication and authorization (single sign-on).

WS-Security

Authentication, encryption, and integrity

WS-Security is a baseline specification and assists in sending secure messages. It illustrates the use of XML Encryption and XML Signature to SOAP headers.

WEB SERVICES ENHANCEMENTS 1.0 FOR MICROSOFT .NET

Microsoft released WSE 1.0 for Microsoft .NET on December 5, 2002. It replaces the WSDK Technical Preview. WSE 1.0 for Microsoft .NET is a new .NET class library by which you can implement the latest Web services protocols, including WS-Security, WS-Routing, DIME, and WS-Attachments.

With the help of WSE, .NET Framework developers can incorporate features such as security, routing, and attachments to their Web services applications. WSE sits on top of the .NET Framework and allows developers to implement the latest Web services protocols in XML Web services. The key part of the WSE is the Microsoft.Web.Services.SoapContext class that provides an interface for examining the WS-Security header and other headers for incoming SOAP messages, and adding WS-Security and other headers for outgoing SOAP messages.

If you install the WSE 1.0 setup, the following items will be installed.

  • The Microsoft.Web.Services assembly (Microsoft.Web.Services.dll) in the application folder.

  • The following elements are added into the Machine.config file by WSE 1.0.

     <mscorlib>    <cryptographySettings>      <cryptoNameMapping>        <cryptoClasses>           <cryptoClass Sha1="System.Security.Cryptography.SHA1Managed" />        </cryptoClasses>        <nameEntry name="SHA1" class="Sha1" />        <nameEntry name="System.Security.Cryptography.SHA1" class="Sha1" />      </cryptoNameMapping>    </cryptographySettings> </mscorlib> 
  • WSE documentation

  • WSE QuickStart Samples Release Notes and Release Notes

The WSE provides the following features for the secure transmission of SOAP messages:

  • Adding Security Credentials to a SOAP Message: By means of WSE, you can add one or more security credentials to a SOAP message. The purpose of adding security credentials to a SOAP message is that it secures the XML Web services over the entire route even though the SOAP message is routed through intermediaries before reaching the final entity. That is, instead of adding security credentials at the transport level, you add the security credentials to the SOAP message (message level).

  • Digitally Signing a SOAP Message: By means of WSE, you can digitally sign a SOAP message so that it facilitates cryptographic verification that a SOAP message has not been altered since it was signed.

  • Encrypting a SOAP Message: By means of WSE, you can encrypt a SOAP message and confirm that only the intended recipient can read the contents of a message.

PROCESS SOAP MESSAGES SIGNED USING A USERNAMETOKEN

Let's see how an XML Web service processes a SOAP message signed using a UsernameToken . The steps are as follows:

  1. In the ASP.NET Web service project add a reference to the Microsoft.Web.Services assembly.

  2. Add the microsoft.web.services configuration section handler to the configuration file. Add a <section> element to the <configuration> section of the needed Web.config file. The following code shows how to add the microsoft.web.services configuration section handler. The type attribute of the <section> element must be on one line, although the following code is broken up for readability.

    [View full width]
     
    [View full width]
    <configuration> <configSections> <section name="microsoft.web.services" type="Microsoft.Web.Services.Configuration. WebServicesConfiguration, Microsoft.Web graphics/ccc.gif .Services, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </configSections> </configuration>
  3. In the Web.config file for the XML Web service, add an <add> element to the <soapExtensionTypes> section. The following code is the configuration entry that must be placed in the Web.config file for the WSE to run with an XML Web service. The type attribute of the <add> element for <soapExtensionTypes> must be on one line, although the following code is broken up for readability.

    [View full width]
     
    [View full width]
    <configuration> <system.web> <webServices> <soapExtensionTypes> <add type="Microsoft.Web.Services.WebServicesExtension, Microsoft.Web.Services graphics/ccc.gif ,Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" priority="1" group="0"/> </soapExtensionTypes> </webServices> </system.web> </configuration>

The Microsoft.Web.Services assembly has to be accessible from within this ASP.NET application; otherwise, the above configuration setting doesn't work. So, the Microsoft.Web.Services assembly has to be either in the bin folder of the ASP.NET application or in the Global Assembly Cache (GAC). In Visual Studio .NET after a reference is made to the Microsoft.Web.Services assembly; set the Copy Local property for the reference to true. This copies the assembly to the bin folder.

Now, let's see how to develop a Web service that processes a SOAP message signed using UsernameToken .

 using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using Microsoft.Web.Services.Security; using Microsoft.Web.Services; using System.Security.Cryptography; namespace WSEUsernameToken {  public class Service1 : System.Web.Services.WebService  { [WebMethod] public string Hello ()  {     SoapContext requestContext = HttpSoapContext.RequestContext;    // Verifies whether a SOAP request was received.    if (requestContext == null)   {         throw new            ApplicationException("Non-SOAP request or the WSE is not properly installed.");   }     UsernameToken Token1 =         GetToken(requestContext.Security);     if (Token1 != null)     {         value = "Hello";     }     return value;   } private UsernameToken GetToken(Security sec)   {     UsernameToken value = null;             if (sec.Tokens.Count > 0)             {                foreach (SecurityToken tok in sec.Tokens)                 {                     value = tok as UsernameToken;                     if (value != null)                     {                      return value;                     }                 }             }     return value;   }  } } 

Since each WS-Security SOAP header may contain zero or more security tokens, we iterate through a for-each loop and return the UsernameToken .

Two major steps are required for the Web services to process SOAP messages signed using a UsernameToken . First, add a class that implements the IPasswordProvider interface. The code is as follows.

[View full width]
 
[View full width]
/* It is recommended to insist that an assembly accessing this class already have graphics/ccc.gif permission to call unmanaged code, since Microsoft.Web.Services is the only assembly that graphics/ccc.gif should call this class. Therefore apply the SecurityPermissionAttribute attribute to the class implementing IPasswordProvider, demanding the UnmanagedCode permission. */ [SecurityPermission(SecurityAction.Demand, Flags= SecurityPermissionFlag.UnmanagedCode)] public class PasswordProvider: IPasswordProvider // Implement the GetPassword method of the IPassword // Provider interface. public string GetPassword(UsernameToken userName) { // This below code is only for pedagogical purpose. // In real time applications the code // typically consults an external database of // (userName,hash) pairs. // Here for simplicity we employ the UTF-8 // encoding of the user name. byte[] encodedUsername = System.Text.Encoding.UTF8.GetBytes (userName.Username); return System.Text.Encoding.GetString(encodedUsername) }

When this class is registered in the Web.config file, the WSE calls the GetPassword method of this class whenever a message is signed using a UsernameToken to get the password for the input user name.

Now, configure the class implementing IPasswordProvider in the Web.config file for the XML Web service, as shown below. The value of the type attribute must be on one line, although this code is broken up for readability.

 <microsoft.web.services>  <security>    <passwordProvider type=      "MyNamespace.PasswordProvider, MyAssemblyName,      Version=1.0.0.0,      Culture=neutral,      PublicKeyToken=81f0828a1c0bb867" />  </security> </microsoft.web.services> 

We configure the MyNamespace.PasswordProvider type to be called whenever a SOAP message signed with a UsernameToken is received for XML Web services affected by this Web.config .

SIGNING A SOAP MESSAGE USING A USERNAME TOKEN

Let's see how an XML Web service client signs a SOAP request using a UsernameToken .

  1. Add a Web reference to Microsoft.Web.Services.dll and System.Web.Services.dll .

  2. Add a Web reference to the Web service that is to receive the SOAP message.

  3. Edit the proxy class to derive from WebServicesClientProtocol . To edit the class, right-click the Reference.cs file in the Solution Explorer, and then click View Code. In the code edit the class from

    [View full width]
     
    [View full width]
    public class Service1 : System.Web.Services.Protocols.SoapHttpClientProtocol to public graphics/ccc.gif class Service1 : Microsoft.Web.Services.WebServicesClientProtocol. /* In Visual Studio .NET, if you click Update Web Reference, the proxy class is graphics/ccc.gif regenerated, the base class is reset to SoapHttpClientProtocol, therefore you have to edit graphics/ccc.gif the proxy class again. */
  4. Add the following using directives to the Web service client code:

     using Microsoft.Web.Services; using Microsoft.Web.Services.Security; 

The client code looks like this:

[View full width]
 
[View full width]
localhost.Service1 proxy = new localhost.Service1(); /* Create a new instance of UsernameToken, specifying the user name, password, and how the graphics/ccc.gif password is sent in the SOAP message.*/ UsernameToken userToken = new UsernameToken(userName, password,PasswordOption.SendHashed); proxy.RequestSoapContext.Security.Tokens.Add(userToken); // Signs the SOAP message using the UsernameToken. Proxy.RequestSoapContext.Security.Elements.Add(new Signature(userToken)); //Call the Web service. label1.Text = proxy.Hello();
WEB SERVICES ENHANCEMENTS 2.0 FOR MICROSOFT .NET

Microsoft released WSE 2.0 for Microsoft .NET on July 15, 2003. [9] It replaces the WSE1.0 Technical Preview which was released on December 5, 2002. With WSE 2.0 for Microsoft .NET, you can implement the latest Web services protocols, including WS-Addressing, WS-Policy, WS-SecurityPolicy, WS-Trust, and WS-SecureConversation.

[9] For more information on WSE 2.0, visit http://msdn.microsoft.com/webservices/building/wse/default.aspx.

The new features added to the WSE 2.0 Technology Preview are as follows.

  1. The WSE version 2.0 provides support for new Web Services specifications including WS-Addressing, WS-Policy, WS-SecurityPolicy, WS-Trust, and WS-SecureConversation.

  2. In WSE version 2.0, you can express the receiving and sending message requirements using configuration files (configuration-based declaration of security or other policies).

  3. The WSE version 2.0 provides the capability to programmatically request a security token using a SOAP message, and that token can be used for a series of SOAP messages between a SOAP message sender and a target Web service.

  4. The WSE version 2.0 supports role-based authorization for SOAP messages by constructing a principal from a security token within the SOAP message.

  5. The WSE version 2.0 provides support for Kerberos tokens. This support is operating system platform dependent.

  6. With SOAP messaging, the WSE version 2.0 supports a flexible mechanism for sending and receiving SOAP messages. This lightweight, message-oriented SOAP programming model facilitates applications to switch between the TCP and HTTP transport protocols easily.

  7. The WSE version 2.0 provides support for XML security tokens, such as XrML and SAML security tokens.

  8. QuickStart samples are provided in C# and Visual Basic languages.

Note that this Technology Preview release is for testing purposes only; the software must not be used in a production environment, must not be redistributed, and is not supported by Microsoft. Get in touch with WSE 2.0 Technology Preview for testing purpose, until the final version of WSE 2.0.

Organizations Involved

Various organizations are involved in the process of finding solutions to the shortcomings of Web services:

  • Worldwide Web Consortium (W3C)

  • Organization for the Advancement of Structured Information Standards (OASIS)

  • Internet Engineering Task Force (IETF)

  • Web services Interoperability Organization (WS-I)

  • Vendors like Microsoft, IBM, Sun, BEA, e-Speak, IONA and Hewlett-Packard

W3C working groups are refining both SOAP 1.1 and WSDL 1.1 specifications. The XML Protocol Working Group and Web Services Description Working Group are working in parallel to standardize SOAP 1.2 and WSDL 1.2, respectively. In addition to XML digital signature and XML encryption, W3C is developing the XML Key Management Specification and a Web service architecture that includes a security framework.

The following are the mission statements of the important organizations involved in developing the foundation for the Web services security standards.

  • OASIS Web Services Security Technical Committee (WSS TC): On April 11, 2002, IBM, Microsoft, and VeriSign announced a set of specifications called WS-Security that extend SOAP security and build on other existing Web services security standards. WSS TC continues to work on the Web Services security foundations as described in the WS-Security specification. The work of the WSS TC will form the necessary technical foundation for higher-level security services, which are to be defined in other specifications.

  • XML Signature WG: The mission of this working group is to develop an XML-compliant syntax used for representing the signature of Web resources and portions of protocol messages (anything referenceable by a URI) and procedures for computing and verifying such signatures. This is a joint working group of the IETF and W3C.

  • XML Encryption Working Group: The mission of this working group is to develop a process for encrypting/decrypting digital content (including XML documents and portions thereof) and XML syntax used to represent both encrypted content and information that enables an intended recipient to decrypt it.

  • XML-Based Security Services Technical Committee (SSTC): This technical committee works on SAML, an XML-based security standard for exchanging authentication and authorization information.

  • Web Services Interoperability Organization (WS-I): WS-I is an open industry organization chartered to promote Web services interoperability across platforms, operating systems, and programming languages. The organization works across the industry and standards organizations to respond to customer needs by providing guidance, best practices, and resources for developing Web services solutions.

OASIS and the W3C focus on the key areas listed in Table 10-4 to form the groundwork of a Web services security framework.

Table 10-4. Web Services Security Standards and Status

Standard (proposed or final)

Standards body and status

WS-Security

OASIS : Forming technical committee, WSS TC

XML Digital Signature

W3C : Completed

XML Encryption

W3C : Final vote in committee

XKMS

W3C : Working draft

SAML

OASIS : Final vote

XACML

OASIS : Committee review

SSL / TLS

IETF : RFC 2246

Kerberos

IETF : RFC 1510



.NET Security and Cryptography
.NET Security and Cryptography
ISBN: 013100851X
EAN: 2147483647
Year: 2003
Pages: 126

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net